简体   繁体   English

BigDecimal.valueOf(float)如何工作?

[英]How does BigDecimal.valueOf(float) work?

I've already looked at this asnwer . 我已经看过这个解决方案了

I was a little confused by the behaviour of BigDecimal.valueOf(float) . 我对BigDecimal.valueOf(float)的行为感到有些困惑。 Here's the example: 这是示例:

System.out.println(BigDecimal.valueOf(20.2f)); //prints 20.200000762939453

Therefore 因此

float f = BigDecimal.valueOf(20.2f)
            .setScale(2, RoundingMode.UP)
            .floatValue();
System.out.println(f); //prints 20.21

Which is defenitely not the behaviour I expected. 这绝对不是我期望的行为。 Is there a way to round up float correctly avoiding such errors? 有没有一种方法可以正确round up浮点数以避免此类错误?

For the description of float and how it utilizes the allocated bits see How many significant digits have floats and doubles in java? 有关float的描述及其如何利用分配的位,请参见java中有多少有效数字具有float和double?

BigDecimal works fine and -- as expected -- keeps all digits it received, but it can't guess the precision of the given argument. BigDecimal可以正常工作,并且-可以预期-保留接收到的所有数字,但是无法猜测给定参数的精度。 Therefore: 因此:

    float f = 20.20f;
    System.out.println("Float: "+f);
    System.out.println("BigDecimal.valueOf: "+BigDecimal.valueOf(f));
    System.out.println("BigDecimal from value: "+new BigDecimal(f, MathContext.DECIMAL32));
    System.out.println("BigDecimal from string: "+new BigDecimal(""+f));;

Prints: 印刷品:

Float: 20.2
BigDecimal.valueOf: 20.200000762939453
BigDecimal from value: 20.20000
BigDecimal from string: 20.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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