[Solved] Getting a percentage of float without digits before decimal point

[ad_1]

You want to get fractional part and truncate it up to two digits. If values are positive and small you can implement it like this:

 private static double Solution(double value) {
    return (long)((value - (long)value) * 100) / 100.0;
 }

Test:

 double[] test = new double[] {
   0.433432,
   0.672919,
   3.826342,
   6.783643, };

 var result = test
   .Select(item => $"{item} -> {Solution(item)}")
   .ToArray();

 Console.Write(string.Join(Environment.NewLine, result));

Outcome:

 0.433432 -> 0.43
 0.672919 -> 0.67
 3.826342 -> 0.82
 6.783643 -> 0.78

Edit: What’s going on in the Solution method:

  • value - (long) value – integer part removing

  • (long) ((...) * 100) – scaling up and truncate

  • () / 100.0 – scaling down back

If we have, say, 1234.5789 these three stages will be:

  • 0.5789 – integer part removing

  • 57 – scale up and truncate

  • 0.57 – scaling down back

2

[ad_2]

solved Getting a percentage of float without digits before decimal point