Since decimal?
does not have a ToString(string format)
overload, the easiest way is to use String.Format
instead which will provide consistent results with the null
case for decimalValue
as well (resulting in an empty string) when compared to your original code:
string value = String.Format("{0:#.##}", decimalValue * 100);
But there are some other considerations for other numbers that you weren't clear on.
If you have a number that does not produce a value greater than 0, does it show a leading zero? That is, for 0.001211
, does it display as 0.12
or .12
? If you want the leading zero, use this instead (notice the change from #.##
to 0.##
):
string value = String.Format("{0:0.##}", decimalValue * 100);
If you have more than 2 significant decimal places, do you want those displayed? So if you had .12113405
would it display as 12.113405
? If so use:
string value = String.Format("{0:#.############}", decimalValue * 100);
(honestly, I think there must be a better formatting string than that, especially as it only supports 12 decimal places)
And of course if you want both leading zeros and multiple decimal places, just combine the two above:
string value = String.Format("{0:0.############}", decimalValue * 100);