Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, how do I get required number of decimal point values without rounding? [duplicate]

Possible Duplicate:
C# Double - ToString() formatting with two decimal places but no rounding

I'm using float numbers and I want to get the number of decimal points without any rounding-off being performed.

For Eg. float x = 12.6789 If I want upto 2 decimal points, then I should get (x = 12.67) and NOT (x = 12.68) which happens when rounding takes place.

Plz suggest which is the best way to do this.

like image 832
AmbujKN Avatar asked Aug 08 '11 14:08

AmbujKN


2 Answers

You should be able to use Math.Truncate() for this:

decimal x = 12.6789m;
x = Math.Truncate(x * 100) / 100; //This will output 12.67
like image 159
Rion Williams Avatar answered Sep 30 '22 04:09

Rion Williams


You can achieve this by casting:

float x = 12.6789;
float result = ((int)(x * 100.0)) / 100.0;
like image 30
Daniel Hilgarth Avatar answered Sep 30 '22 05:09

Daniel Hilgarth