Rounding

R

Rookie

In java is there a way to round a double to 2 decimal places for
example money $2.50 not $2.502453651

Thank-you
Rookie
 
E

Erwin Moller

Rookie said:
In java is there a way to round a double to 2 decimal places for
example money $2.50 not $2.502453651

Hi Rookie,

Check out Bigdecimal in java.math.

An exampleprogram follows.
Be sure to read:
http://java.sun.com/j2se/1.3/docs/api/java/math/BigDecimal.html

the part about BigDecimal.ROUND_HALF_UP or whatever roundmethod suits you is
important to read, so you know what you are doing. (I never before was
aware of all these roundmethods. Saying just: 'round it' doesn't make a lot
of sense if you think it over.)

Good luck,
regards,
Erwin


import java.math.*;

public class TestDecimalPlaces
{
public static void main(String[] args)
{

double d = 2435.14565;
int decPlaces = 2;
BigDecimal bd =
(new BigDecimal(d)).setScale(decPlaces,BigDecimal.ROUND_HALF_UP);

String strFormattedd = bd.toString();

System.out.println("Received:"+d);
System.out.println("formatted:"+strFormattedd);

}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top