decimal l = 50.0M;
I have seen other answers suggesting that the M is to explicitly state the type as decimal - What does the M stand for in C# Decimal literal notation?
However when the type, of variable, is exclusively stated, why should there be a suffix? I can see the relevance of the suffix when the type, of variable, isn't specified, like:
var l = 50.0M
when the type, of variable, is exclusively stated, why should there be a suffix?
You need a cast only in situations when the value that you are assigning has a decimal point. In your case, 50.0
represents a literal of type double
. You can avoid suffix by adding a cast, like this
decimal l = (decimal)50.0; // Do not do this!
but this may result in conversion errors:
decimal d = (decimal)1.23456789123456789;
Console.WriteLine(d); // Prints 1.23456789123457
decimal e = 1.23456789123456789M;
Console.WriteLine(e); // Prints 1.23456789123456789
Note that the following will compile without a suffix or a cast, because int
to decimal
conversion never loses precision:
decimal l = 50;
Another place where you may want M
suffix is in expressions that manipulate decimals:
decimal tenPercentBroken = myDecimal * 0.1; // Does not compile
decimal tenPercentCorrect = myDecimal * 0.1M; // Compiles fine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With