Java BigDecimal / Double precision error -


i'm trying simulate atm amount input in java, ie. user keeps inputting "1", amount shown should be:

0.00 0.01 0.11 1.11 11.11 111.11 

i tried both double , bigdecimal processing:

println( ((new bigdecimal(current)).multiply(new bigdecimal(10)).add(new bigdecimal(0.01))).setscale(2, roundingmode.half_up).tostring()) )  println( "" + double.parsestring(current) * 10 + 0.01 ) 

however both seems show instead:

0.00 0.01 0.11 1.11 11.1 <<< missing 0.01 @ end 111.01 

are both due precision rounding error (i thought bigdecimal not have problem) or doing wrong?

the simplest option might record input string. after each key press append new character end of it, , format number creating bigdecimal , dividing 100.

string input = "111111"; bigdecimal value = new bigdecimal(input).divide(new bigdecimal(100)); // 1111.11 

that said, i've tried code in loop , appears work fine. you'll need post code showing how generate current.

string current = "0.00"; (int = 0; < 10; i++) {     current = (new bigdecimal(current).multiply(new bigdecimal(10)).add(new bigdecimal(0.01))).setscale(2, roundingmode.half_up).tostring();     system.out.println(current); }  //    0.01 //    0.11 //    1.11 //    11.11 //    111.11 //    1111.11 //    11111.11 //    111111.11 //    1111111.11 //    11111111.11 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -