Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.format() rounding a double with leading zeros in digits - Java

Tags:

java

rounding

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.

like image 700
tifi90 Avatar asked Jul 14 '20 06:07

tifi90


People also ask

How do I keep last 0s after decimal point for double data type in Java?

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.

How do you add a leading zero to a string in Java?

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.

How do you do 2 decimal places in Java?

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 (%).


Video Answer


1 Answers

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.

like image 200
Unmitigated Avatar answered Oct 19 '22 21:10

Unmitigated