Question
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.
Solution
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
OTHER TIPS
This approach should work for both positive an negative values of x:
int log = (x == 0) ? 1 : (int)(Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(x)))));
int result = (int)(((x < 0) ? Math.Floor(x / log) : Math.Ceiling(x / log)) * log);
Can't give you a c#
-specific answer, but generally what you're looking for is log10
, whatever it's called in c#
. If you want to operate on number.
If this is about output, you can, indeed, operate on string, skipping/adjusting first number, etc.
This should to the trick:
// val is the value
var log = Math.Floor(Math.Log10(val));
var multiplier = Math.Pow(10, log);
var result = Math.Ceiling(val/multiplier)*multiplier;