Circle any n-digit number to (n-1) zero digits

It is a pity that it is difficult to formulate.

I need to round like this:

12 -> 10 152 -> 200 1538 -> 2000 25000 -> 30000 etc. 

Twisting my head, but I can’t figure out how to do this. Should work for any number of digits. Has anyone got an elegant way for him?

C # or vb.net

+4
source share
6 answers

I think you should try something like this:

 public int Round( int number) { int power = number.ToString().Length - 1; int sz = Math.Pow(10, power); int rounded = (int)Math.Round( number / sz ); return rounded * sz; } 

The idea is to get the size of the nearest 10 power, available along the length of the number, expressed as a string. Then divide the number by this power, leaving it equal to 1.2, and then round it using the Math.Round method, and restore the size by resetting it to power.

Like the previous answer ...

+3
source

How about this:

  double num = 152; int pow = (int)Math.Log10(num); int factor = (int)Math.Pow(10, pow); double temp = num / factor; double result = Math.Round(temp) * factor; 
+4
source

I would do it like this:

 double d = 25000; int power = d.ToString().Length - 1; double multipler = Math.Pow(10,power); d = Math.Round(d / multipler) * multipler; Console.WriteLine(d); 
+1
source

One way could be

  • Convert number to decimal
  • Divide it by 10 ^ (n-1) (where n is the number of digits)
  • Now use the round function ( Decimal.Round )
  • Multiply again by 10 ^ (n-1)
0
source
 int MakeOneSigFig(int value) { int neg = 1; if(value <= 10 && value >= -10) { return value; } if(value == int.MinValue) { value = int.MaxValue; neg = -1; } if(value < 0) { value = -value; neg = -1; } int mult = 10; // start at 10 because we've got 'firstDigit = value / 10' below while(value > 99) { value /= 10; mult *= 10; } int firstDigit = value / 10; if(value % 10 >= 5) firstDigit++; return neg * firstDigit * mult; } 

This is equivalent to MidpointRounding.AwayFromZero . This method does not perform double mathematical or string conversions. If you do not want to loop, you can replace this with the if block below. It would be more efficient, but more code and not so easy to read.

 if(value < 100) { mult = 10; } else if(value < 1000) { mult = 100; value /= 10; } else if(value < 10000) { mult = 1000; value /= 100; } else if(value < 100000) { mult = 10000; value /= 1000; } // etc. 
0
source

Divide the number by 10n and round the result, then multiply the result by 10n;

 int MyRound(int num) { double divisor = Math.Pow(10, num.ToString().Length - 1); return (int)(Math.Round(num / divisor, MidpointRounding.AwayFromZero) * divisor); } 

Please note that when rounding due to the banker's rounding, by default, we should use MidpointRounding.AwayFromZero .

0
source

Source: https://habr.com/ru/post/1334304/


All Articles