Get the last 2 decimal places without rounding

In C #, I am trying to get the last two decimal places of a double with NO rounding. I tried everything from Math.Floor to Math.Truncate and nothing works.

Sample results that I would like:

 1,424.2488298 -> 1,424.24 53.5821 -> 53.58 10,209.2991 -> 10,209.29 

Any ideas?

+7
source share
5 answers

Well, mathematically, it's simple:

 var f = 1.1234; f = Math.Truncate(f * 100) / 100; // f == 1.12 

Move decimal two places to the right, drop to int to truncate, move it left two places. There may be ways in this, but I canโ€™t look now. You can generalize it:

 double Truncate(double value, int places) { // not sure if you care to handle negative numbers... var f = Math.Pow( 10, places ); return Math.Truncate( value * f ) / f; } 
+22
source

My advice: stop using double first . If you need decimal rounding, then the odds are good, you should use decimal . What is your app?

If you have a double, you can do it like this:

 double r = whatever; decimal d = (decimal)r; decimal truncated = decimal.Truncate(d * 100m) / 100m; 

Note that this method will not work if the absolute double value is greater than 792281625142643375935439504, because multiplication by 100 will fail. If you need to handle large values, you will need to use special methods. (Of course, by the time the double is so large, you are still superior to its ability to represent values โ€‹โ€‹with two digits after the decimal point).

+14
source
  double d = Math.Truncate(d * 100) / 100; 
+5
source

Common decision:

  public static double SignificantTruncate(double num, int significantDigits) { double y = Math.Pow(10, significantDigits); return Math.Truncate(num * y) / y; } 

Then

  double x = 5.3456; x = SignificantTruncate(x,2); 

It will produce the desired result x=5.34 .

+2
source
 Math.Round(NumberToRound - (double)0.005,2) 

ie

 Math.Round(53.5821 - (double)0.005,2) // 53.58 Math.Round(53.5899 - (double)0.005,2) // 53.58 Math.Round(53.5800 - (double)0.005,2) // 53.58 
+2
source

All Articles