Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiples of 10,100,1000,... C#

Tags:

c#

integer

I want an integer to be multiples of 10,100,1000 and so on...

For eg double val = 35 then I want int 40
val = 357 then I want int val = 400
val = 245,567 then I want int val = 300,000
val = 245,567.986 then also I want int = 300,000

Is there anything in C# that can help in generating these integer

Basic logic that I can think is : Extract the first integer , add 1 to it. Count the total number of digits and add zeros (totalno -1 ).

Is there any better way ?

I want to assign these values to the chart axis. I am trying to dynamically create the axis label values based on datapoints of the charts.

like image 868
ssal Avatar asked Sep 16 '09 14:09

ssal


People also ask

What happens when you multiply by 10100 or 1000?

When we multiply by 10, 100 and a 1000 we shift all the digits to the left. One place left for 10, two places left for 100 and three places left for 1000. When we divide by 10, 100 and a 1000 we do the opposite and shift all the digits to the right instead.

What are multiples of 1000?

The first 5 multiples of 1000 are 1000, 2000, 3000, 4000, 5000. The sum of the first 5 multiples of 1000 is 15000 and the average of the first 5 multiples of 1000 is 3000. Multiples of 1000: 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 and so on.

How do you multiply by multiples of 100?

Multiplying by a Multiple of 100 To multiply a whole number by 100, simply write two 0 digits on the end of it. To multiply a number by a multiple of 100, multiply the number by the digits in front of the two 0 digits and then write two 0 digits on the end. 400 is a multiple of 100. 400 = 4 × 100.


1 Answers

This should do what you want where x is the input:

        double scale = Math.Pow(10, (int)Math.Log10(x));
        int val = (int)(Math.Ceiling(x / scale) * scale);

Output:

 35          40
 357         400
 245567      300000
 245567.986  300000

If you want it to cope with negative numbers (assuming you want to round away from 0):

        double scale = (x == 0 ? 1.0 : Math.Pow(10, (int)Math.Log10(Math.Abs(x))));
        int val = (int)(Math.Ceiling(Math.Abs(x) / scale) * scale)*  Math.Sign(x);

Which gives:

-35         -40
 0           0
 35          40
 357         400
 245567      300000
 245567.986  300000
like image 173
JDunkerley Avatar answered Sep 21 '22 00:09

JDunkerley