I have a double value which is very close to 1. How can I cast it to 1 ?
I do this
double myValue = 0.9999; double a = Math.round(myValue); int intValue = (int)a;
But it return 1 even if myValue is in the the range [0.5 , 1], so I lose precision. I want it return 1 only if myValuse is so close to 1 (exp : 0.999) and it should not return 1 when myValue is 0.6 for example.
Thank u for ur help
Try something like:
final double threshold = 0.0001; if (Math.abs(a - 1) < threshold) intValue = 1; else intValue = 0;
This will set intValue to 1 when a is “close enough to 1” (ie. within threshold of 1), and will set intValue to 0 otherwise (assuming you want it rounded to 0 if it’s not within the threshold).
You can adjust the value of the threshold to tighten or loosen the range around 1 that it’ll handle.
Alternatively, if you want to round to 1 if it’s just above a given value, you can do eg.:
if (a >= 0.9999) intValue = 1; else intValue = 0;
Math.round is specifically designed to do that. If you want to do something different, you’ll have to code it yourself.
For instance, if you want .8 and higher to round to 1 instead of .5 and higher (see note below about negative numbers):
double myValue = 0.9999; int base = (int)Math.floor(myValue); double remainder = myValue - base; int intValue = remainder >= .8 ? base + 1 : base;
- Get the whole number part (Math.floor) into base, truncating the fractional portion
- Get just the fractional portion into remainder
- Add one to base if the fractional portion is >= .8
Obviously, you’ll have to choose the point at which you round up, since you want something other than .5.
If you want to handle negative numbers, it’s more complicated, since Math.floor will always go toward positive infinity. So you may have to branch on the sign of myValue and use Math.ceil instead when negative (and adjust the myValue – base accordingly). And then there’s the entire question of whether the same kind of cutoff applies, or is it symmetrical? Should that cutoff be -0.8 or -0.2? I leave handling negative values in the manner you want as an exercise for you…
That said, this feels more complicated than it should be. Perhaps something like what’s described in Dawood ibn Kareem’s comment would work for what you’re trying to do. (May have to be + 0.3 rather than – 0.3 when handling negatives. Or not.)