I've asked this question already here in the comments:
How to round a number to n decimal places in Java.
I'm trying to convert a double into a string with a fixed number of decimal places. In the question above the solution is quite simple. When using
String.format("%.4g", 0.1234712)
I get the expected result, a number rounded to 4 digits:
0.1235
But when there are zeros after the decimal dot:
String.format("%.4g", 0.000987654321)
This will return:
0,0009877
It looks like the function is ignoring the leading zeros in the digits.
I know that I could just define a new DecimalFormat but I want to understand this issue. And learn a bit about the syntax.
To be able to print any given number with two zeros after the decimal point, we'll use one more time DecimalFormat class with a predefined pattern: public static double withTwoDecimalPlaces(double value) { DecimalFormat df = new DecimalFormat("#. 00"); return new Double(df.
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
Use %.4f
to perform the rounding you want. This format specifier indicates a floating point value with 4 digits after the decimal place. Half-up rounding is used for this, meaning that if the last digit to be considered is greater than or equal to five, it will round up and any other cases will result in rounding down.
String.format("%.4f", 0.000987654321);
Demo
The %g
format specifier is used to indicate how many significant digits in scientific notation are displayed. Leading zeroes are not significant, so they are skipped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With