Convert from double to long without Round Java -
i'm trying convert random double long without rounding or truncating it. first change double string, know how many decimal places there , change value long. problem number of last decimal place not correct , don't know reason , how can change it. here code:
double z=(double) myrandom(1, 20); long test; string s = double.tostring(z); test=(long) (math.pow(10, s.length()-s.indexof(".")-1)*z); system.out.println("z: "+z); system.out.println("double converted long: "+test);
and that's output:
d: 19.625014811604743
double converted long: 19625014811604744
d: 9.143326452202839
double converted long: 9143326452202838
d: 5.8964228376511105
double converted long: 58964228376511104
d: 15.045936360299917
double converted long: 15045936360299918
d: 14.147950026532694
double converted long: 14147950026532694
editing current implementation:
double z=(double) myrandom(1, 20); string s = double.tostring(z); //convert string (edited comments) s = s.replaceall(".", ""); //remove period long test = long.parselong(s); //convert long
or if want random long
recommend using random.nextlong()
instead.
Comments
Post a Comment