Avatar billede fredand Forsker
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
Avatar billede arne_v Ekspert
09. juli 2004 - 20:40 #1
Try:

x = ((int)(x * 100))/100.0;

or:

x = ((int)(x * 100 + 0.005))/100.0;
Avatar billede arne_v Ekspert
09. juli 2004 - 20:40 #2
The last one should be:

x = ((int)(x * 100 + 0.5))/100.0;
Avatar billede arne_v Ekspert
09. juli 2004 - 20:41 #3
Without +0.5 it truncates down, with +0.5 it round to nearest.
Avatar billede arne_v Ekspert
09. juli 2004 - 20:41 #4
BTW unless you have space constraints then double is usable preferrable to float.
Avatar billede fredand Forsker
09. juli 2004 - 20:43 #5
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
Avatar billede arne_v Ekspert
09. juli 2004 - 20:47 #6
The Math class has ceil/floor/round methods but only to no decimals.
Avatar billede fredand Forsker
10. juli 2004 - 15:50 #7
Thanks for your time mate!

But please give me a svar so I can reward you!

Fredrik
Avatar billede arne_v Ekspert
10. juli 2004 - 15:59 #8
svar
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester