Home > Net >  How do I force max 4 decimals without rounding up in C# / .NET
How do I force max 4 decimals without rounding up in C# / .NET

Time:05-10

Example variables:

var example1 =  1,12345638282382384;
var example2 = 12,12;
var example3 = 30,19999;

Result what I want:

example1 = 1,1234;
example2 = 12,12; // 12,1200 would be better but isn't that important)
example3 = 30,1999;

What is the issue? I got more than 4 decimal numbers, but I want to only see 4 decimals. I search around the internet, but I only see examples of rounding up & full numbers getting a comma, while my example already have the comma's.

Furthermore, I am a student/junior developer and at least tried to search around before asking, hopefully someone knows the answer.

CodePudding user response:

Math.Round allows you to specify the rounding behavior you want, eg Math.Round(example1,4,MidpointRounding.ToZero) produces 1.1234.

C# > var example1 =  1.12345638282382384;

C# > Math.Round(example1,4)
╭─✔──────────────────────────────────────────────────────────────╮
│ 1.1235                                                         │
╰────────────────────────────────────────────────────────────────╯
C# >  Math.Round(example1,4,MidpointRounding.ToZero)
╭─✔──────────────────────────────────────────────────────────────╮
│ 1.1234                                                         │
╰────────────────────────────────────────────────────────────────╯

CodePudding user response:

If you desperately want to avoid rounding, I'd do what user18387401 suggested in their comment, but also use some string formatting to always display 4 decimals (even if those 4 decimals are 0000):

public static double TruncateDigits(double value, int places)
{
    var integral = Math.Truncate(value);
    var fraction = value - integral;
    
    var multiplier = (double)Math.Pow(10, places);
    var truncatedFraction = Math.Truncate(fraction * multiplier) / multiplier;

    return integral   truncatedFraction;
}

// Usage
Console.WriteLine(string.Format("{0:N4}", TruncateDigits(example1, 4)));

Link to dotnetfiddle showing this off

If you're OK with always rounding down, I'd highly suggest thinking about rounding instead of doing this as rounding does the same as this does. Panagiotis Kanavos' answer shows how to do that

  • Related