1

I want to convert any input float having any number of decimals, to string with only 2 decimals; if I do:

(13399.25f).ToString("#.00") returns "13399,25" -> OK

BUT,

(133995.25f).ToString("#.00") returns "133995,30" -> KO!

Also, I see that

(133995.25d).ToString("#.00") returns "133995,25" -> OK

Here, it says that float has a "precision" of 7 digits... the number 133995.25f has 8 digits ... So, is Precision the number of digits that a number has in total ? I thought it was the number of digits for the decimal part only...:

https://www.codingame.com/playgrounds/14640/c-professional---numbers/numeric-types-in-c

Also, the "scale" indicates that the number can be as high as ±3.4x1038 far far less than my number... Why is that ?

Also, this article confuses me even more: C# float.ToString Rounding Values

It suggests to use "G9" format, but if my input has a nr. of decimals different from 2, I would not get an output string with 2 decimals...

Thanks !

Roger
  • 333
  • 2
  • 13
  • 1
    [Have a read of this](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) and you will (hopefully) be enlightened! – Matthew Watson Nov 07 '19 at 18:23
  • https://stackoverflow.com/a/58507658/11482040 – André Sanson Nov 07 '19 at 18:25
  • 1
    The highest number that can be represent and precision are two different things. Float point numbers are represented more or less like scientific notation, you have the significant value (7 digits precision in this case), and an exponent (which ditates the higest number representable). So yeah, it's 7 digits in total, not decimal places. – Magnetron Nov 07 '19 at 18:29
  • Also consider using double instead of float. – André Sanson Nov 07 '19 at 18:33
  • I though https://stackoverflow.com/questions/588004/is-floating-point-math-broken would be reasonable duplicate... but it actually does not explain why .NET formatting does rounding that way... The "floating math is broken" explains "precision" so at least would help you a bit... – Alexei Levenkov Nov 07 '19 at 19:06
  • I suggest reading [the documentation to `ToString`](https://learn.microsoft.com/en-us/dotnet/standard/base-types/formatting-types?view=netframework-4.8) and the format specifiers and just try things. – Heretic Monkey Nov 07 '19 at 19:21

0 Answers0