简体   繁体   中英

Java DecimalFormat rounding down

I am using DecimalFormatter to read in formatted decimal string values and convert them to float. However, when I run:

    DecimalFormat formatter = new DecimalFormat("####,####.00");
    String floatStr = "177,687.71";
    float val1 = formatter.parse(floatStr).floatValue();
    System.out.println(val1);

...I get 177678.7 instead of 177678.71. Why is this? How do I avoid rounding the hundredths place?

Thanks!

You appear to need more precision than a float to represent that number.

Taking the formatter out of the picture:

Float.parseFloat("177687.71");
177687.7 // Ouch

Double.parseDouble("177687.71");
177687.71 // Ok

It seems that you'll need to use a double instead.

If this is for representing money though as @Dawood is suggesting , then yes, do not use floating types to represent money, since they are estimations and will accumulate errors over time. A format like BigDecimal would be more appropriate, or even just storing an integer representing cents. Money is not something that you want to subject to rounding errors.

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