Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate number of digit of double value in C#

Tags:

c#

How can i truncate the leading digit of double value in C#,I have tried Math.Round(doublevalue,2) but not giving the require result. and i didn't find any other method in Math class.

For example i have value 12.123456789 and i only need 12.12.

like image 292
Firoz Avatar asked Sep 15 '09 12:09

Firoz


People also ask

How do you truncate a two digit number?

To truncate a number to 1 decimal place, miss off all the digits after the first decimal place. To truncate a number to 2 decimal places, miss off all the digits after the second decimal place.

How many decimal places does a double have in C?

double has 15 decimal digits of precision.

How do you truncate a double to two decimal places?

DecimalFormat("#. ##") - Here, I entered two hash symbols(##) after the decimal point. Hence, this will truncate the number up to two decimal places. This will work for both Positive & Negative values.

How do you find the number of double digits?

Count how often you must divide the number by 10 until it's smaller than 1 -> that gives you the digits before the decimal point. Then count how often you must multiply the original number by 10 until it equals the Math. Floor-result -> that gives you the digits behind the decimal points.


2 Answers

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
like image 20
LukeH Avatar answered Oct 10 '22 15:10

LukeH


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.

like image 155
Jon Skeet Avatar answered Oct 10 '22 17:10

Jon Skeet