I’m trying to convert and exponential number 1.11111117E+9 which is actually a 10 digit number ‘1111111111’. When I’m trying to convert this exponential number using decimal.TryParse method it is making last 3 digits as zero and giving the number as ‘111111000‘. This is happening with any 10 digit number.
decimal amount;
decimal.TryParse("1.11111117E+9", NumberStyles.Any, null, out amount);
This is weird but I’m not able to figure out what’s the issue here, can anybody tell me what’s wrong in this?
Edit:
Sorry for the misleading question. As Henrik mentioned in his answer is exactly what I’m facing.
float f = 1111111111;
string s = f.ToString();
decimal amount;
decimal.TryParse(s, NumberStyles.Any, null, out amount);
This will always return 1111111000? How do I address this issue to get the correct value? Change it to Double or Decimal from float datatype is the solution or anything else?
It’s easy to round-trip a float value…
Now
fandgwill be the same… but that doesn’t mean that either value is exactly 1111111111… because that value can’t be represented as a float. The nearest value exactly representable as a float is 1111111168… which is why you’re getting the 7 at the end of the scientific representation.Basically, you shouldn’t be using
floatfor this in the first place. From the docs for System.Single:So trying to store a 10 digit number and expecting it to be stored exactly is a fool’s errand.
It’s hard to say whether you should be using
doubleordecimal– it depends on what value you’re really trying to store. If it’s a “natural” value like weight or height, I’d go fordouble. If it’s a “human” value like a price, I’d usedecimal.