0

for example let's just say I have a:

var value = "0000000000002022"

how can I get : 20.22

DnyaneshSurya
  • 187
  • 1
  • 1
  • 14

2 Answers2

2

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(number / 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 here. If you need to be as accurate as possible, for example when working with money, then maybe use decimal instead (or, make the decision to represent the money as a whole number, representing the minor units of currency your country uses)

MindSwipe
  • 7,193
  • 24
  • 47
1

by using convert

Int16.Parse(value);
Convert.ToDecimal(int1)/100;