-1

Executed in c# interactive

> 200M.ToString()
"200"
> 200.0M.ToString()
"200.0"
> 200.000000000000M.ToString()
"200.000000000000"

I was mind blown by this. Why this happens?

Shadow
  • 2,089
  • 2
  • 23
  • 45
  • 1
    Isn't that the point of the `decimal` type? – Pranav Hosangadi Dec 15 '22 at 17:50
  • 1
    "_Why C# decimal.ToString behaves differently when literal has .0_" Because the designers of the System.Decimal type decided to do so, and there are apparently certain application scenarios where preserving trailing decimal zeros is useful, otherwise the designers of this type wouldn't have made System.Decimal behave this way... –  Dec 15 '22 at 17:51
  • 1
    As a side note, the more interesting question would be why many System.Decimal methods (like ToString(), for example) do not reveal the existence of a negative zero (e.g., -0, -0.0, etc.) despite the bit representation of the decimal preserving the sign even for zero values, and thus the sign being discoverable in the publicly accessible bit data of a decimal. Wonders of the world... –  Dec 15 '22 at 17:55
  • 1
    @MySkullCaveIsADarkPlace You already answered your side note: "Because the designers of the System.Decimal type decided to do so". Probably because -0 doesn't make much sense to human eyes. – Webs Dec 15 '22 at 17:57
  • @Webs, i know. Just wanted to highlight a quirk of System.Decimal ;-D –  Dec 15 '22 at 17:57

1 Answers1

2

200 and 200.0 are the same numerically (200m == 200.0m returns true), of course, but "200" and "200.0" are certainly not the same string, and certainly will not pass a string.Equals() check

Decimal class always retains things like precision and scale. Decimal is intended for monetary calculations, so we definitely want it to exhibit this sort of meticulous behavior

Narish
  • 607
  • 4
  • 18