5

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.

Community
  • 1
  • 1
AmbujKN
  • 121
  • 9
  • What have you tried? What didn't work? Please post your code and explain where you are having problems. – Oded Aug 08 '11 at 14:02

3 Answers3

8

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
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
3

You can achieve this by casting:

float x = 12.6789;
float result = ((int)(x * 100.0)) / 100.0;
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

There is probably a framework call for this, but you could always write one like:

//Scale up, floor, then round down.
//ie: 1.557 
//    scaled up: 155.7
//    floord:  155
//    scaled down: 1.55
public float MyTruncate(float f, int precision){
   float scale = precision * 10;
   return (Math.Floor(f * scale)) / scale;
}
Sheldon Warkentin
  • 1,706
  • 2
  • 14
  • 31