Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the relevance of M suffix on a decimal literal [duplicate]

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
like image 302
Social Developer Avatar asked Mar 08 '23 20:03

Social Developer


1 Answers

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
like image 135
Sergey Kalinichenko Avatar answered Apr 07 '23 18:04

Sergey Kalinichenko