Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate Decimal number not Round Off [duplicate]

Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)

I want to truncate the decimals like below

i.e.

  • 2.22939393 -> 2.229
  • 2.22977777 -> 2.229
like image 536
ManojN Avatar asked Dec 01 '08 03:12

ManojN


People also ask

How do I truncate without rounding?

To get rid of some decimal places without and rounding, use TRUNC(), which is short of truncate. It takes two arguments: the value and the number of decimal places. Whatever is to the right of the specified decimal location is simply discarded. For example, =TRUNC(12.119999, 2) evaluates to 12.11.

How do you truncate a decimal?

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 do you truncate a double to two decimal places?

Shift the decimal of the given value to the given decimal point by multiplying 10^n. Take the floor of the number and divide the number by 10^n. The final value is the truncated value.

Do you round when you truncate?

To round down, the formula is =ROUNDDOWN(num,digits) . When Excel truncates, it chops off part of the entered number and performs no rounding at all. So if you input 345.679 and format the number for no decimal points, it cuts off the digits after the decimal point.


2 Answers

You can use Math.Round:

decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229 

Or you can use ToString with the N3 numeric format.

string roundedNumber = number.ToString("N3"); 

EDIT: Since you don't want rounding, you can easily use Math.Truncate:

Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229 
like image 51
Christian C. Salvadó Avatar answered Sep 23 '22 13:09

Christian C. Salvadó


double d = 2.22977777; d = ( (double) ( (int) (d * 1000.0) ) ) / 1000.0 ; 

Of course, this won't work if you're trying to truncate rounding error, but it should work fine with the values you give in your examples. See the first two answers to this question for details on why it won't work sometimes.

like image 37
Bill the Lizard Avatar answered Sep 22 '22 13:09

Bill the Lizard