java - How to cast to integer and don't lose precision -


i have double value close 1. how can cast 1 ? this

 double myvalue = 0.9999;  double = math.round(myvalue);  int intvalue = (int)a; 

but return 1 if myvalue in the range [0.5 , 1], lose precision. want return 1 if myvaluse close 1 (exp : 0.999) , should not return 1 when myvalue 0.6 example.

thank u ur help

math.round designed that. if want different, you'll have code yourself.

for instance, if want .8 , higher round 1 instead of .5 , higher (see note below negative numbers):

double myvalue = 0.9999; int base = (int)math.floor(myvalue); double remainder = myvalue - base; int intvalue = remainder >= .8 ? base + 1 : base; 

live example

there, we:

  1. get whole number part (math.floor) base, truncating fractional portion
  2. get fractional portion remainder
  3. add 1 base if fractional portion >= .8

obviously, you'll have choose point @ round up, since want other .5.

if want handle negative numbers, it's more complicated, since math.floor go toward positive infinity. may have branch on sign of myvalue , use math.ceil instead when negative (and adjust myvalue - base accordingly). , there's entire question of whether same kind of cutoff applies, or symmetrical? should cutoff -0.8 or -0.2? leave handling negative values in manner want exercise you...

that said, feels more complicated should be. perhaps what's described in dawood ibn kareem's comment work you're trying do. (may have + 0.3 rather - 0.3 when handling negatives. or not.)


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -