Truncate number of digit of double value in C#

EDIT: It's been pointed out that these approaches round the value instead of truncating. It's hard to genuinely truncate a double value because it's not really in the right base... but truncating a decimal value is more feasible.

You should use an appropriate format string, either custom or standard, e.g.

string x = d.ToString("0.00");

or

string x = d.ToString("F2");

It's worth being aware that a double value itself doesn't "know" how many decimal places it has. It's only when you convert it to a string that it really makes sense to do so. Using Math.Round will get the closest double value to x.xx00000 (if you see what I mean) but it almost certainly won't be the exact value x.xx00000 due to the way binary floating point types work.

If you need this for anything other than string formatting, you should consider using decimal instead. What does the value actually represent?

I have articles on binary floating point and decimal floating point in .NET which you may find useful.


What have you tried? It works as expected for me:

double original = 12.123456789;

double truncated = Math.Truncate(original * 100) / 100;

Console.WriteLine(truncated);    // displays 12.12

This code....

double x = 12.123456789;
Console.WriteLine(x);
x = Math.Round(x, 2);
Console.WriteLine(x);

Returns this....

12.123456789
12.12

What is your desired result that is different?

If you want to keep the value as a double, and just strip of any digits after the second decimal place and not actually round the number then you can simply subtract 0.005 from your number so that round will then work. For example.

double x = 98.7654321;
Console.WriteLine(x);
double y = Math.Round(x - 0.005, 2);
Console.WriteLine(y);

Produces this...

98.7654321
98.76

Tags:

C#