-2

I have an api that receive a decimal value as string.

e.g: "1.96"

I am parsing this string value with this code:

decimal.TryParse("1,96", out myDecimalVar)

But I need the following decimal value: 1.96000

How can I do it without Math.Round? Because Math.Round returns 1.97000

Tks!

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215

3 Answers3

3

Unlike double and float, decimal is a BCD (Binary Decimal), so you can play a trick:

 // Be sure, that your current culture uses "," (comma)
 // as a decimal separator (e.g. Russian, ru-Ru culture)
 decimal.TryParse("1,96", out myDecimalVar);

 // add up a special form of zero
 myDecimalVar += 0.00000m;

 // 1,96000
 Console.Write(myDecimalVar);

for details, please, see

https://msdn.microsoft.com/en-us/library/system.decimal(v=vs.110).aspx

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.

So we have myDecimalVar being turned into 196000 integer number with -5 scale factor.

A more natural way, however, is to parse as it is, and represent as you want with a help of formatting:

 decimal.TryParse("1,96", out myDecimalVar);
 ...
 Console.Write(myDecimalVar.ToString("F5")); // 5 digits after the decimal point
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

If you need it as a string then:

`       string v = "1.96";
        decimal d;
        decimal.TryParse(v, out d);
        Console.Write(d.ToString("f4"));
`
afrose
  • 169
  • 1
  • 9
0

You have vary alternatives

decimal myDecimalVar;
decimal.TryParse("1,96", out myDecimalVar);
Console.WriteLine(myDecimalVar.ToString("0.00000")); // 1,96000
Console.WriteLine(myDecimalVar.ToString("F5"));      // 1,96000

as already answered.

Marco Luongo
  • 397
  • 4
  • 13