because i want to compare it with original value later in my project.
...then you will need to store the number of decimal places the original value had. Once the value is a float, this information is lost. The float representations of 2.5
, 2.50
and 2.500
are exactly the same.
So, basically, you have the following possibilities (in order of preference):
- Don't do a string comparison between the old and the new value. Convert both values to float and then compare them (with a margin of error since floats are not precise).
- Store the number of decimal places of the old value and then use
myFloat.ToString("F" + numDecimals.ToString())
to convert it to a string.
- Store the value as a string instead of a float. Obviously, you won't be able to do math on that value.
Alternatively, if you do not insist on using floats, decimals
might suit your purpose: The do store the number of significant digits:
decimal x = Decimal.Parse("2.50", CultureInfo.InvariantCulture);
decimal y = Decimal.Parse("2.500", CultureInfo.InvariantCulture);
Console.WriteLine(x.ToString()); // prints 2.50
Console.WriteLine(y.ToString()); // prints 2.500