Home > front end >  Float.toString(value) has seemingly arbitrary round off point?
Float.toString(value) has seemingly arbitrary round off point?

Time:03-31

When executing the Float.toString(68.1992069267325) I expected java to return 68.19921. Instead I receive 68.1992. After further investigation, it seems that the roundoff point is somewhat arbitrary, rather than at a 5 boundary (For example, I expect 68.199205 rounded up, 68.19920499999 rounded down)

> println Float.toString(68.1992069267325)
> println Float.toString(68.1992070000000)
> println Float.toString(68.1992071000000)
> println Float.toString(68.1992072000000)
> println Float.toString(68.1992073000000)
> println Float.toString(68.1992074000000)
> println Float.toString(68.1992075000000)
> println Float.toString(68.1992076000000)
> println Float.toString(68.1992077000000)
> println Float.toString(68.1992078000000)
> println Float.toString(68.1992079000000)
> println Float.toString(68.1992079267325)
68.1992
68.1992
68.1992
68.1992
68.1992
68.19921
68.19921
68.19921
68.19921
68.19921
68.19921
68.19921

CodePudding user response:

According to the javadocs:

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type float. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument f. Then f must be the float value nearest to x; or, if two float values are equally close to x, then f must be one of them and the least significant bit of the significand of f must be 0.

One thing to keep in mind here is that the float type is a rough approximation to the mathematical concept of real numbers. One of the quirks of this approximation is that there is not a float representation for every real number.

From your output, I guess that neither 68.1992069267325 nor 68.1992070000000 can be represented exactly as a float. Both have the same representation as 68.1992, so that's what is printed in both cases.

CodePudding user response:

It is most likely that there is no exact representation with a float of some of those real numbers you've printed.

If your concern is to give a proper representation of a real number and defining a rounding up behavior then you should use the BigDecimal class. This class is specifically designed to overcome the limitations of the floating-point representation as it allows you to define an arbitrary-precision signed decimal number.

CodePudding user response:

Use String.format("%.06f", 68.1992069267325)

  •  Tags:  
  • java
  • Related