Reputation:
We need to round like this
0.15 => 0.5
0.5 => 0.5
1 => 1
152 => 1
1538 => 1
25000 => 1
How to achieve this ? This is what i was trying
decimal number = 10;
decimal rounded = Math.Ceiling(number / 10000 * 20) / 20;
This don't work as expected if number is 100000 or greater ,because give me 10 as the result
Upvotes: 0
Views: 95
Reputation: 186668
Something like that:
public static Double Clamp(Double n) {
return n > 1.0 ? 1.0 : n < 0 ? 0 : n;
}
However. in that case the 1st sample will be
0.15 => 0.15
as the question states "...to the nearest number between 0..1".
Edit: an extended version of Clamp
could be something like that:
public static Double Clamp(Double value, Double min, Double max) {
//TODO: you may want to check here if min > max
return value > max ? max : value < min ? min : value;
}
public static Double Clamp(Double value) {
return Clamp(value, 0.0, 1.0);
}
if you're insisting on 0.15 => 0.5
it may be the case that you actually want
Clamp(value, 0.5, 1.0); // [0.5..1], not [0..1]
Upvotes: 2
Reputation: 27357
I'm guessing it should be 0.15 => 0.5, as Dmitry said. In that case, you can do this:
private double RoundIt(double value)
{
if (value <= 0)
return 0;
if (value >= 1)
return 1;
return value;
}
Upvotes: 0