For Programmers: Free Programming Magazines  


Home > Archive > Java Help > December 2004 > rounding









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author rounding
Adrien Martel

2004-12-20, 4:00 pm

Hi,

I am attempting to round a number (float) to 2 decimal digits in java. How
is this possible?

Thanks,

--

Adrien Martel
cs2


klynn47@comcast.net

2004-12-20, 8:58 pm

One approach would be to multiply the number by 100, cast it to an int,
then divide it by 100.0. This would truncate instead of round.

Tony Morris

2004-12-20, 8:58 pm

> I am attempting to round a number (float) to 2 decimal digits in java. How
> is this possible?


http://www.xdweb.net/~dibblego/java...nswers.html#q28

--
Tony Morris
http://xdweb.net/~dibblego/


Boudewijn Dijkstra

2004-12-21, 8:57 am

<klynn47@comcast.net> schreef in bericht
news:1103571572.279608.114830@c13g2000cwb.googlegroups.com...
> One approach would be to multiply the number by 100, cast it to an int,
> then divide it by 100.0. This would truncate instead of round.


Add 50 before multiplying and you will effectively round. Note that a float
itself can never be rounded to exactly two decimal digits, unless the
correctly rounded fraction is .0, .25, .50 or .75. This is because float and
double are numbers of base 2, not of base 10.


Paul O'Donnell

2004-12-21, 8:58 pm

Adrien Martel wrote:
> Hi,
>
> I am attempting to round a number (float) to 2 decimal digits in java. How
> is this possible?
>
> Thanks,
>
> --
>
> Adrien Martel
> cs2
>
>


Check out the NumberFormat class. java.text.NumberFormat in the API. If
you have any trouble figuring out how to use it let us know. I'd be
happy to give you an example.

Paul

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com