0

I need get fractional part of double like int and only two numbers. My code

(int)Math.Floor(val * 100 - (int)val * 100)

but this can (int)val * 100 may be out of range of int or long. Ok. If i try

(int)Math.Floor((val - (int)val) * 100)

Return value may be incorrect. For example:

double val = 56.9;
int retVal = (int)Math.Floor((val - (int)val) * 100);
// retVal = 89, because (val - (int)val) return 0.899999999675

How correct get fractional part of double like int?

Andrey Ganin
  • 349
  • 1
  • 10

4 Answers4

2

Try this extensions method:

public static int GetFrac2Digits(this double d)
{
    var str = d.ToString("0.00", CultureInfo.InvariantCulture);
    return int.Parse(str.Substring(str.IndexOf('.') + 1));
}
denys-vega
  • 3,522
  • 1
  • 19
  • 24
0

try this

double val = 56.9;
double result=0;
int retVal = (int)Math.Floor((val - (int)val) * 100);
// retVal = 89, because (val - (int)val) return 0.899999999675
int FrctPart=result.ToString().Split('.')[1]
Dgan
  • 10,077
  • 1
  • 29
  • 51
0

Like this maybe?

decimal d = (decimal)val;
int retVal = Math.Floor((d - Math.Floor(d)) * 100);
// 59.9 --> 90
// 123.456 --> 45
marsze
  • 15,079
  • 5
  • 45
  • 61
0

You could also use Math.Truncate instead of casting to int:

double val = 56.9;
int retVal = (int)Math.Round((val-Math.Truncate(val)) * 100);
// retVal is now 90
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111