为什么我的float被截断? [英] Why is my float being truncated?

查看:163
本文介绍了为什么我的float被截断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

27.8675309 IEEE754.htmlrel =nofollow> IEEE 754 Converter 将我输入的值更改为 27.86753 。同样,当解析一个具有相同值的字符串时,Java会丢弃最后两位数字。

  Float.parseFloat(27.8675309) //结果是浮点值为27.86753 

我不确定Decimal representation IEEE转换器实际上是(这是一个浮动?),但我希望它给了我可能最大的数字:


  1. 是浮动值

  2. 不超过我输入的原始值


  3. 我希望Java能在也就是说,我希望上面的代码行可以返回一个等于 27.8675308 的float值,或者是一个更接近我的原始输入的更大的float值只是下降小数位。我在这里错过了什么?

    解决方案



    如果你看27.8675309(27.867530822753906作为双精度)的二进制表示:

      01000001110111101111000010110100 


    $ b

    下一个最高值是:

    pre $ code > 01000001110111101111000010110101

    产生27.867533(27.86753273010254为双倍),而下一个最低值为: p>

      01000001110111101111000010110011 



    < (27.867528915405273为双倍)

    浮点数中没有足够的位浮点代表中间的任何值,所以你的价值是十进制舍入到27.867530


    Entering a value such as 27.8675309 into the "Decimal representation" field of the IEEE 754 Converter changes the value I entered to 27.86753. Likewise, Java drops the last two digits when a parse a string with the same value.

    Float.parseFloat("27.8675309") // Results in a float value of 27.86753
    

    I am not sure what the "Decimal representation" of the IEEE converter actually is (is it a float?) but I would expect it to give me the biggest number possible that:

    1. Is a float value
    2. Does not exceed the original value I entered

    I would expect Java to behave in a similar fashion, that is, I would expect the line of code above to return a float value equal to 27.8675308 or an even larger float value that is closer to my original input instead of just dropping decimal places. What am I missing here?

    解决方案

    This is as expected.

    If you look at the binary representation of 27.8675309 (27.867530822753906 as a double):

    01000001110111101111000010110100
    

    the next highest value is:

    01000001110111101111000010110101
    

    which yields 27.867533 (27.86753273010254 as a double), and the next lowest value is:

    01000001110111101111000010110011
    

    which yields 27.867529 (27.867528915405273 as a double)

    There simply aren't enough bits in the mantissa of a Float to represent any value in between, so your value is rounded down in decimal to 27.867530

    这篇关于为什么我的float被截断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆