Declaration suffix for decimal type

C#.Net

C# Problem Overview


If I want to use a decimal literal in code, I have seen that there exists the m-suffix (where m stands for money). Is this appropriate for any decimals or is there a more general assignment (d stands for double, that is for sure not the right thing although a direct conversion is supported).

object decimalValue=2m;

Please note, I took the object-assignment as example, because in the case of ...

decimal decimalValue=2;

... it's implicitly clear that 2 should be interpreted as decimal through the compiler.

m seems to be ok, http://msdn.microsoft.com/en-us/library/364x0z75(VS.71).aspx">msdn</a> uses it as example for the decimal type.

C# Solutions


Solution 1 - C#

Documented in the C# language specification, chapter 2.4.4:

float f = 1.2f;
double d = 1.2d;
uint u = 2u;
long l = 2L;
ulong ul = 2UL;
decimal m = 2m;

Nothing for int, byte, sbyte, short, ushort.

Solution 2 - C#

Without a suffix, a numerical real literal will be a Double. The m suffix specifies that a numeric real literal should be a Decimal.

This is actually important to know, since arithmetic on floating point values (such as Double) is imprecise. For instance:

object decimalValue=(5.32 + 2.23);

Here, decimalValue will actually contain a Double, with the unexpected value of 7.5500000000000007! If I want 7.55, I could do this:

object decimalValue=(5.32m + 2.23m);

To answer your question about whether there is a more general suffix, m is the only suffix for Decimal in C#. It might stand for money as you mentioned, but they had do use something other than d, since that's used by Double!

Further reading: decimal (C# Reference)

Solution 3 - C#

Short answer to Declare Decimal in C#

decimal firstMoney = 141.28m;

O/P: 141.28

decimal secondMoney = 100.00m;

O/P: 100

For more refer MSDN.

Hope helps someone.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHCLView Question on Stackoverflow
Solution 1 - C#Hans PassantView Answer on Stackoverflow
Solution 2 - C#Brian MacKayView Answer on Stackoverflow
Solution 3 - C#Shaiju TView Answer on Stackoverflow