Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Sorry hard to formulate.

I need to round like this:

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

Twisting my head, but can't see how to make this. Must work for any n number of digits. Anyone got an elegant method for it?

c# or vb.net

like image 881
bretddog Avatar asked Jan 05 '11 05:01

bretddog


People also ask

How do you round if a number is 0?

If the digit is 0, 1, 2, 3, or 4, do not change the rounding digit. All digits that are on the righthand side of the requested rounding digit become 0. If the digit is 5, 6, 7, 8, or 9, the rounding digit rounds up by one number.

What is the 5 rounding rule?

If the first digit to be dropped is a digit greater than 5, or if it is a 5 followed by digits other than zero, the excess digits are all dropped and the last retained digit is increased in value by one unit.

What are n digit numbers?

An n digit number is a positive number with exactly n digits. Nine hundred distinct n digit numbers are to be formed using only the three digits 2, 5, and 7. The smallest value of n for which this is possible is. (a) 6.

What are the rules to round off a number to n significant figures?

Rules for Rounding-off a NumberDiscard all digits to the right of nth significant digit. less than half a unit in nthplace, leave the nth digit unchanged. greater than half a unit in the nth place, increase the nth digit by unity.


2 Answers

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;
like image 198
logicnp Avatar answered Oct 18 '22 20:10

logicnp


I think you should try with 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 by the length of the number expressed as a string. Then divide the number by that power, leaving it like 1,2 and then round it using the Math.Round method and restore the size by remultiplying it to the power.

Much like the previous answer...

like image 41
David Conde Avatar answered Oct 18 '22 19:10

David Conde