简体   繁体   中英

Convert double to exaclty two decimal place in java

I want to convert a dobule to exaclty two places.I have answers to lhe same query but none of them satisfies for my problem.

This is the code i am using :

Double d=15.99965754;
System.out.println("Value before formatting is : "+d);
String value=new DecimalFormat("##.00").format(d);
System.out.println("The value after formatting is :" +Double.parseDouble(value));

And the output i am getting is

Value before formatting is : 15.99965754 The value after formatting is :16.0

but what i actually looking forward to print is :

Value before formatting is : 15.99965754 The value after formatting is :16.00

No matter what the double value is i should get the decimal to exactly two places.

Do not parse value, just print

System.out.println("The value after formatting is :" + value);

another way to get the same resut

System.out.printf("The value after formatting is : %.2f", d);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM