Home > Mobile >  How to remove the leading 0s and divide the remaining value by 100, use a dot separator between the
How to remove the leading 0s and divide the remaining value by 100, use a dot separator between the

Time:04-19

for example let's just say I have a:

var value = "0000000000002022"

how can I get : 20.22

CodePudding user response:

Mathematically speaking, it doesn't matter how many zeroes are before your number, their the same, so 0000002 = 2 is true. We can use this fact to simply parse our string to a number, and then do the division, but we have to be a little careful in which number type we use, because doing (int) 16 / (int) 5 will result in 3, which obviously isn't correct, but integer division does that. So, just to be sure we don't loose any precision, we'll use float

string value = "0000000000002022";
if (float.TryParse(value, out var number))
{
    // Successfully parsed our string to a float
    Console.WriteLine(value / 100);
}
else
{
    // We failed to parse our string to a float :(
    Console.WriteLine($"Could not parse '{value}' to a float");
}

Always use TryParse except if you're 110% sure the given string will always be a number, and even then, circumstances can (and will, this is software development after all) change.

Note: float isn't infinitely large, it has a maximum and minimum value, and anything outside that range cannot be represented by a float. Plus, floating point numbers also have a caveat: They're not 100% accurate, for example 0.1 0.2 == 0.3 is false, you can read up more on the topic enter image description here

  • Related