c# – Cast a Double Variable to Decimal

c# – Cast a Double Variable to Decimal

You only use the M for a numeric literal, when you cast its just:

decimal dtot = (decimal)doubleTotal;

Note that a floating point number is not suited to keep an exact value, so if you first add numbers together and then convert to Decimal you may get rounding errors. You may want to convert the numbers to Decimal before adding them together, or make sure that the numbers arent floating point numbers in the first place.

You can cast a double to a decimal like this, without needing the M literal suffix:

double dbl = 1.2345D;
decimal dec = (decimal) dbl;

You should use the M when declaring a new literal decimal value:

decimal dec = 123.45M;

(Without the M, 123.45 is treated as a double and will not compile.)

c# – Cast a Double Variable to Decimal

use default convertation class: Convert.ToDecimal(Double)

Leave a Reply

Your email address will not be published.