-1

I need a way to round down a float up to a specific number of decimal places. Math.Round will round up if the number after the cut is larger than 6, and Math.Floor does not work with decimal places.

Basically if I have 2.566321, I want the code to return 2.56. The only way I know that this can be done is to convert the float to a string and use string.format but I would rather not do that if possible.

Thanks.

TheGateKeeper
  • 4,420
  • 19
  • 66
  • 101

1 Answers1

2

A brute force way might be to multiply by 10^n where n is the number of decimal places you want, cast to int (which does truncation rather than rounding), then cast back to float and divide by 10^n again.

visually:

2.566321 * 10^2 = 2.566321 * 100 = 256.6321

(int) 256.6321 = 256

(float) 256 / 10^2 = (float) 256 / 100 = 2.56

Quick attempt at the code:

public float Truncate(float value, int decimalPlaces) {
   int temp = (int) (value * Math.Pow(10, decimalPlaces));
   return (float) temp / Math.Pow(10, decimalPlaces);
}

I haven't tested this, but that should get you going.

jeffdt
  • 66
  • 3