java - Wrong double variable incrementing -
this question has answer here:
- is floating point math broken? 20 answers
i made simple code whis keeps adding 0.1 zero. code:
static double num = 0; public static void main(string[] args) { num+=0.1; system.out.println(num); try { thread.sleep(100); } catch (interruptedexception e) { e.printstacktrace(); } main(null); } }
this outputs:
0.1 0.2 0.30000000000000004 0.4 0.5 0.6 0.7 0.7999999999999999 0.8999999999999999 0.9999999999999999 1.0999999999999999 ...
but want output this:
0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1 ...
any ideas why or how fix please?
try:
system.out.printf("%.1f" , num);
instead of:
system.out.println(num);
this limit decimal places right of decimal 1 place. if wanted 3 decimal places use %.3f
Comments
Post a Comment