简体   繁体   中英

How to change the precision of a float conversion?

I am trying to convert float value to 32 bit unsigned long value and facing the problem of loss of value. long v = (long) f;

Here when f is 4294967295 ((2^32) -1). The conversion to long returns 4294967296 instead of 4294967295 because float conversion is precised to 7 decimal places. I need precision to 9 decimal places. Is there any way to achieve this?

Quote from Java Puzzlers: Traps, Pitfalls, and Corner Cases book:

Floating-point operations return the floating-point value that is closest to their exact mathematical result. Once the distance between adjacent floating-point values is greater than 2, adding 1 to a floating-point value will have no effect, because the half-way point between values won't be reached. For the float type, the least magnitude beyond which adding 1 will have no effect is 2^25, or 33,554,432; for the double type, it is 2^54, or approximately 1.8 × 10^16.

So basicly, if you want to represent big numbers, float is a bad idea. Above 2^25 it is not able to represent at least every other integer. It get worse the bigger the number gets.

The best option for you would be to use BigDecimal instead.

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