What's the best practice to round a float to 2 decimals?
I was working with statistics in Java 2 years ago and I still got the codes of a function that allows you to round a number to the number of decimals that you want. Now you need two, but maybe you would like to try with 3 to compare results, and this function gives you this freedom.
/**
* Round to certain number of decimals
*
* @param d
* @param decimalPlace
* @return
*/
public static float round(float d, int decimalPlace) {
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.floatValue();
}
You need to decide if you want to round up or down. In my sample code I am rounding up.
Hope it helps.
EDIT
If you want to preserve the number of decimals when they are zero (I guess it is just for displaying to the user) you just have to change the function type from float to BigDecimal, like this:
public static BigDecimal round(float d, int decimalPlace) {
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd;
}
And then call the function this way:
float x = 2.3f;
BigDecimal result;
result=round(x,2);
System.out.println(result);
This will print:
2.30
How to round to 2 decimals with Python?
You can use the round
function, which takes as its first argument the number and the second argument is the precision after the decimal point.
In your case, it would be:
answer = str(round(answer, 2))
round up to 2 decimal places in java?
Well this one works...
double roundOff = Math.round(a * 100.0) / 100.0;
Output is
123.14
Or as @Rufein said
double roundOff = (double) Math.round(a * 100) / 100;
this will do it for you as well.
Formatting a number with exactly two decimals in JavaScript
To format a number using fixed-point notation, you can simply use the toFixed method:
(10.8).toFixed(2); // "10.80"
var num = 2.4;
alert(num.toFixed(2)); // "2.40"
Note that toFixed()
returns a string.
IMPORTANT: Note that toFixed does not round 90% of the time, it will return the rounded value, but for many cases, it doesn't work.
For instance:
2.005.toFixed(2) === "2.00"
UPDATE:
Nowadays, you can use the Intl.NumberFormat
constructor. It's part of the ECMAScript Internationalization API Specification (ECMA402). It has pretty good browser support, including even IE11, and it is fully supported in Node.js.
const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
console.log(formatter.format(2.005)); // "2.01"
console.log(formatter.format(1.345)); // "1.35"
How to round each item in a list of floats to 2 decimal places?
"%.2f"
does not return a clean float. It returns a string representing this float with two decimals.
my_list = [0.30000000000000004, 0.5, 0.20000000000000001]
my_formatted_list = [ '%.2f' % elem for elem in my_list ]
returns:
['0.30', '0.50', '0.20']
Also, don't call your variable list
. This is a reserved word for list creation. Use some other name, for example my_list
.
If you want to obtain [0.30, 0.5, 0.20]
(or at least the floats that are the closest possible), you can try this:
my_rounded_list = [ round(elem, 2) for elem in my_list ]
returns:
[0.29999999999999999, 0.5, 0.20000000000000001]
Round a double to 2 decimal places
Here's an utility that rounds (instead of truncating) a double to specified number of decimal places.
For example:
round(200.3456, 2); // returns 200.35
Original version; watch out with this
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)
) or large integer part (e.g. round(90080070060.1d, 9)
). Thanks to Sloin for pointing this out.
I've been using the above to round "not-too-big" doubles to 2 or 3 decimal places happily for years (for example to clean up time in seconds for logging purposes: 27.987654321987 -> 27.99). But I guess it's best to avoid it, since more reliable ways are readily available, with cleaner code too.
So, use this instead
(Adapted from this answer by Louis Wasserman and this one by Sean Owen.)
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
Note that HALF_UP
is the rounding mode "commonly taught at school". Peruse the RoundingMode documentation, if you suspect you need something else such as Bankers’ Rounding.
Of course, if you prefer, you can inline the above into a one-liner:new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()
And in every case
Always remember that floating point representations using float
and double
are inexact.
For example, consider these expressions:
999199.1231231235 == 999199.1231231236 // true
1.03 - 0.41 // 0.6200000000000001
For exactness, you want to use BigDecimal. And while at it, use the constructor that takes a String, never the one taking double. For instance, try executing this:
System.out.println(new BigDecimal(1.03).subtract(new BigDecimal(0.41)));
System.out.println(new BigDecimal("1.03").subtract(new BigDecimal("0.41")));
Some excellent further reading on the topic:
- Item 48: "Avoid
float
anddouble
if exact answers are required" in Effective Java (2nd ed) by Joshua Bloch - What Every Programmer Should Know About Floating-Point Arithmetic
If you wanted String formatting instead of (or in addition to) strictly rounding numbers, see the other answers.
Specifically, note that round(200, 0)
returns 200.0
. If you want to output "200.00", you should first round and then format the result for output (which is perfectly explained in Jesper's answer).
JavaScript displaying a float to 2 decimal places
float_num.toFixed(2);
Note:toFixed()
will round or pad with zeros if necessary to meet the specified length.
Related Topics
Calculating the Angle Between a Line and the X-Axis
Android: Google Maps API - Change Position of Maps Toolbar
Libavcodec.So: Has Text Relocations
How to Close Another App in Android
Encrypt with Node.Js Crypto Module and Decrypt with Java (In Android App)
What Is the Use of Basecolumns in Android
Finding Signed Angle Between Vectors
How to Create My Own Appender in Log4J
Runtime.Exec():Reboot in Android
Why Does Bitmapfactory.Decodebytearray Return Null
Onintercepttouchevent Only Gets Action_Down
Why Menuitemcompat.Getactionprovider Returns Null
Android Studio - Failed to Find Target Android-18