-1

I want to convert a Float number to String without losing its precision.

When I convert 40075016.68557849 to String, it is being represented as 4.0075016E7.

I need to get it represented exactly as the entered value, that is "40075016.68557849".

I've tried String.valueOf(), Float(40075016.68557849f).toString() but nothing is working in the proper way.

  • 2
    Try entering your number here https://www.h-schmidt.net/FloatConverter/IEEE754.html then you will see that you lose the precision, because float is not capable of storing the number. – leonardkraemer May 29 '19 at 03:22
  • 1
    First, that's too many digits for a `float` (or a `Float`); you'd need to use a `double` (or `Double`). Second, `float` and `double` are not, in general, capable of _exact_ representations of decimal factions (except those which happen to be multiples of a negative power of 2). If you need exact representations of arbitrary decimal fractions, you need `BigDecimal`. – Kevin Anderson May 29 '19 at 03:27
  • 1
    `40075016.68557849f` is already imprecise. Nothing to do with `Float.toString()` at all. Try `BigDecimal.valueOf("40075016.68557849").toString()`. – user207421 May 29 '19 at 03:53
  • For curious one: this magic number is equatorial Earth circumference in meters. – radioxoma Jun 13 '23 at 23:49

2 Answers2

1

BigDecimal

If you need to maintain your fractional number precisely, you cannot use the floating-point types float/Float and double/Double. Floating-point technology trades away accuracy for speed of execution. And there are limits to the size of numbers they can hold.

Instead use BigDecimal. Much slower but accurate.

new BigDecimal( "40075016.68557849" ) 
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

If the number does not have to be human-readable then you can use Double.doubleToLongBits() and Double.longBitsToDouble() and then print the long. This preserves the exact bit pattern of the value. In particular, it preserves the exact pattern of a NaN, in case that is important.

Another option may be Double.toHexString().

If the number needs to be human readable then check this document. It explains that printing to 17 decimal digits (%.17g or %.17f) is enough to guarantee that reading back the string will produce the same number.

Daniel Junglas
  • 5,830
  • 1
  • 5
  • 22