09. juli 2004 - 20:37
Der er
7 kommentarer og 1 løsning
How to set number of decimals again!
Dough! I was to fast and did not ask the question right ;-) I got code like this: float x public void updateX(int x) { this.x = this.x + (x/100f); //Just for testing System.out.println((this.x + (x/100f))); } I only want 2 decimal for x but I get like 8!! For eg if I call updateX like below when x is 0.04: updateX(1); I get this value at x: 0.049999997 So what I need is a nice and neat float with just 2 decimals not a String, my fault Arne, sorry! So the result needs to be a float with the correct sum of 0.04 + (1/100f) = 0.05f. I'm pretty sure that this is possible but I do not remember how! So if any one have the solution please let me know! Fredrik
Annonceindlæg tema
Offentlig digitalisering
Fra effektivisering til digital suverænitet. Hvordan skaber det offentlige en digital fremtid med AI, sikkerhed og kontrol i centrum?
Try: x = ((int)(x * 100))/100.0; or: x = ((int)(x * 100 + 0.005))/100.0;
The last one should be: x = ((int)(x * 100 + 0.5))/100.0;
Without +0.5 it truncates down, with +0.5 it round to nearest.
BTW unless you have space constraints then double is usable preferrable to float.
Hello! Seems ok but I'm pretty sure that there is a class that may do this, but if you dont know about it I'm pretty sure I'm wrong ;-) Fredrik
The Math class has ceil/floor/round methods but only to no decimals.
Thanks for your time mate! But please give me a svar so I can reward you! Fredrik
Kurser inden for grundlæggende programmering