Search code examples
c#stringfloating-pointformat

Incorrect rounding of float when using ToString("F1")


I have a float value: 12345.6489

When I format this using:

(12345.6489f).ToString("F1")

Then I get a result of

12345.7

But this is incorrect, since it should be 12345.6.

Does anyone understand why this might occur? Another hint is that casting to double before I format returns the correct result, and if my float value is a little smaller, for example 1234.6489, then too I get the correct result.


Solution

  • This seems to be related to a question I asked some time ago: Round-twice error in .NET's Double.ToString method

    Note that if you call .ToString("G") on your number, it is correctly rounded to 12345.65. If you round the rounded number, to one decimal, the problem occurs.

    When I investigated my own question earlier, I also found some examples that couldn't be explained as round-twice errors, so check that thread as well.

    Addition: Note that any number that can be represented (exactly) by a float, can also be represented (with a lot of zero bits) by a double. One can use the following trick (which the question also mentions):

    float x = 12345.6489f;
    string trick = ((double)x).ToString("F1");