Decimal ToString() conversion issue in C#
Decimal
preserves any trailing zeroes in a Decimal
number. If you want two decimal places instead:
decimal? decimalValue = .1211m;
string value = ((decimal)(decimalValue * 100)).ToString("#.##")
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
or
string value = ((decimal)(decimalValue * 100)).ToString("N2")
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
From System.Decimal
:
A decimal number is a floating-point value that consists of a sign, a numeric value where each digit in the value ranges from 0 to 9, and a scaling factor that indicates the position of a floating decimal point that separates the integral and fractional parts of the numeric value.
The binary representation of a Decimal value consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the 96-bit integer and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10, raised to an exponent ranging from 0 to 28. Therefore, the binary representation of a Decimal value is of the form, ((-296 to 296) / 10(0 to 28)), where -296-1 is equal to MinValue, and 296-1 is equal to MaxValue.
The scaling factor also preserves any trailing zeroes in a Decimal number. Trailing zeroes do not affect the value of a Decimal number in arithmetic or comparison operations. However, >>trailing zeroes can be revealed by the ToString method if an appropriate format string is applied<<.
Remarks:
- the decimal multiplication needs to be casted to decimal, because
Nullable<decimal>.ToString
has no format provider as Chris pointed out you need to handle the case that the
Nullable<decimal>
isnull
. One way is using theNull-Coalescing-Operator
:((decimal)(decimalValue ?? 0 * 100)).ToString("N2")
This article from Jon Skeet is worth reading:
Decimal floating point in .NET (seach for keeping zeroes if you're impatient)
Since you using Nullable<T>
as your decimal
, Nullable<T>.ToString()
method doesn't have overloading takes parameters that you can use for formatting.
Instead of, you can explicitly cast it to decimal
and you can use .ToString()
method for formatting.
Just use "0.00"
format in your .ToString()
method.
decimal? decimalValue = .1211M;
string value = ((decimal)(decimalValue * 100)).ToString("0.00");
Console.WriteLine(value);
Output will be;
12.11
Here is a DEMO
.
As an alternative, you can use Nullable<T>.Value
without any conversation like;
string value = (decimalValue * 100).Value.ToString("0.00");
Check out for more information from Custom Numeric Format Strings
Alternatively, you can specify the format "F2", like so: string val = decVal.ToString("F2")
as this specifies 2 decimal places.