mint
mint

Reputation: 3433

Get Last 2 Decimal Places with No Rounding

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?

Upvotes: 10

Views: 38961

Answers (6)

Burak Ulker
Burak Ulker

Reputation: 1

Octane i generalized your answer, it does not suffer from exceeding max values.. works like a charm :)

int dec = 4; 
return Math.Round(val - (decimal)(5 / Math.Pow(10,dec+1)), dec)

Upvotes: 0

Octane
Octane

Reputation: 1240

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

Upvotes: 2

Eric Lippert
Eric Lippert

Reputation: 660098

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.)

Upvotes: 15

Ed Swangren
Ed Swangren

Reputation: 124642

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;
}

Upvotes: 26

user425495
user425495

Reputation:

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.

Upvotes: 2

ionden
ionden

Reputation: 12776

 double d = Math.Truncate(d * 100) / 100;

Upvotes: 6

Related Questions