Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate Float value up to two decimal point in java

DecimalFormat hisFormat = new DecimalFormat("########.##");
hisFormat.setRoundingMode(RoundingMode.DOWN);

Float x=12345678.12345f;
System.out.println("Float Value " + hisFormat.format(x));

Above code print "Float Value" as 12345678 I need 12345678.12

How can I get my result? Please let me know.

like image 834
Shailendra Avatar asked Feb 04 '26 01:02

Shailendra


1 Answers

Use Double other than Float, or you will lose precision

DecimalFormat hisFormat = new DecimalFormat("######.##");
hisFormat.setRoundingMode(RoundingMode.DOWN);
Double x = 12345678.12345;
System.out.println("Float Value " + hisFormat.format(x));

Use Float the result is 12345678

Use Double the result is 12345678.12

like image 58
Haifeng Zhang Avatar answered Feb 06 '26 20:02

Haifeng Zhang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!