In C#, I\'m trying to get the last two decimal places of a double with NO rounding. I\'ve tried everything from Math.Floor
to Math.Truncate
and nothin
Math.Round(NumberToRound - (double)0.005,2)
i.e
Math.Round(53.5821 - (double)0.005,2) // 53.58
Math.Round(53.5899 - (double)0.005,2) // 53.58
Math.Round(53.5800 - (double)0.005,2) // 53.58
A general solution:
public static double SignificantTruncate(double num, int significantDigits)
{
double y = Math.Pow(10, significantDigits);
return Math.Truncate(num * y) / y;
}
Then
double x = 5.3456;
x = SignificantTruncate(x,2);
Will produce the desired result x=5.34
.
Well, mathematically it's simple:
var f = 1.1234;
f = Math.Truncate(f * 100) / 100; // f == 1.12
Move the decimal two places to the right, cast to an int to truncate, shift it back to the left two places. There may be ways in the framework to do it too, but I can't look right now. You could generalize it:
double Truncate(double value, int places)
{
// not sure if you care to handle negative numbers...
var f = Math.Pow( 10, places );
return Math.Truncate( value * f ) / f;
}
My advice: stop using double
in the first place. If you need decimal rounding then odds are good you should be using decimal
. What is your application?
If you do have a double, you can do it like this:
double r = whatever;
decimal d = (decimal)r;
decimal truncated = decimal.Truncate(d * 100m) / 100m;
Note that this technique will fail if the absolute value of the double is larger than 792281625142643375935439504, because the multiplication by 100 will fail. If you need to handle values that large then you'll need to use special techniques. (Of course, by the time a double is that large, you are well beyond its ability to represent values with two digits after the decimal place anyway.)
double d = Math.Truncate(d * 100) / 100;