string - Decimal ToString() conversion issue in C# -
i facing problem when try convert decimal? string. scenario is
decimal decimalvalue = .1211; string value = (decimalvalue * 100).tostring(); current result : value = 12.1100
expected result : value = 12.11
please let me know, reason this.
decimal preserves trailing zeroes in decimal number. if want 2 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 floating-point value consists of sign, numeric value each digit in value ranges 0 9, , a scaling factor indicates position of floating decimal point separates integral , fractional parts of numeric value.
the binary representation of decimal value consists of 1-bit sign, 96-bit integer number, , scaling factor used divide 96-bit integer , specify portion of decimal fraction. scaling factor implicitly number 10, raised exponent ranging 0 28. therefore, binary representation of decimal value of form, ((-296 296) / 10(0 28)), -296-1 equal minvalue, , 296-1 equal maxvalue.
the scaling factor preserves trailing zeroes in decimal number. trailing zeroes not affect value of decimal number in arithmetic or comparison operations. however, >>trailing zeroes can revealed tostring method if appropriate format string applied<<.
remarks:
- the decimal multiplication needs casted decimal, because
nullable<decimal>.tostringhas no format provider as chris pointed out need handle case
nullable<decimal>null. 1 way usingnull-coalescing-operator:((decimal)(decimalvalue ?? 0 * 100)).tostring("n2")
this article jon skeet worth reading:
decimal floating point in .net (seach keeping zeros if you're impatient)
Comments
Post a Comment