-1

I have a requirement to perform rounding of values with negative precision. As far as I've checked, Math.Round() in .NET does not support negative precision. For example:

ROUND(43.34566,-1) 

The above returns 40.

Please suggest how to achive this.

Sabuncu
  • 5,095
  • 5
  • 55
  • 89
Girish
  • 81
  • 1
  • 10
  • divide by 10, round, multiply by 10 – sashkello Aug 05 '13 at 07:17
  • Negative precision is really just a convention of languages/libraries that support rounding to the nearest 10, 100, etc. Try searching for what you actually want to do. – Jonathon Reinhart Aug 05 '13 at 07:18
  • Thanks sashkello. This is working fine even I've adopted same technique,how can we go for generic implementation. Here precision is -1 it might change with diffrent cases. – Girish Aug 05 '13 at 07:32

3 Answers3

1

ROUND(43.34566 / 10,0) * 10 will work; generalise as appropriate.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Quite simple really:

Math.Round(num / Math.Pow(10.0, -(precision))) * Math.Pow(10.0, -(precision));
//this won't work for positives but oh well
It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
1

Move the comma to the precision you want to give back and then round.

        double n = 43.34566;
        double roundingValue = -1;
        double precision = Math.Pow(10, roundingValue);
        n *= precision;
        double result  = Math.Round(n, 0) / precision;
OriolBG
  • 2,031
  • 2
  • 18
  • 21