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 nothing is working.
Samples of the results I'd like:
1,424.2488298 -> 1,424.24
53.5821 -> 53.58
10,209.2991 -> 10,209.29
Any ideas?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With