truncating java doubles

J

Jeremy Watts

Hi,

How do you truncate java doubles? I am trying to convert a double to a
number thats rounded to 3 decimal places - i can do this using BigDecimals
easily but cant seem to find anything to do the same with a double.


Thanks
 
M

Manish Pandit

Hi,

How do you truncate java doubles? I am trying to convert a double to a
number thats rounded to 3 decimal places - i can do this using BigDecimals
easily but cant seem to find anything to do the same with a double.

Thanks

NumberFormat might be the solution what you're looking for (http://
java.sun.com/j2se/1.4.2/docs/api/java/text/NumberFormat.html).

-cheers,
Manish
 
S

sengsational

Hi,

How do you truncate java doubles? I am trying to convert a double to a
number thats rounded to 3 decimal places - i can do this using BigDecimals
easily but cant seem to find anything to do the same with a double.

Thanks

double d = Math.PI * 20000;
NumberFormat f = NumberFormat.getInstance();
f.setMinimumFractionDigits(3);
System.out.println("d:" + d);
System.out.println("a:" + f.format(d));
System.out.println("b:" + ((int)(d * 1000))/ 1000d);
 
W

www

sengsational wrote:

double d = Math.PI * 20000;
NumberFormat f = NumberFormat.getInstance();
f.setMinimumFractionDigits(3);
System.out.println("d:" + d);
System.out.println("a:" + f.format(d));
System.out.println("b:" + ((int)(d * 1000))/ 1000d);

You will see more difference(due to rounding) between a: and b:

double d = Math.PI * 20000 + 0.0006;
NumberFormat f = NumberFormat.getInstance();
f.setMinimumFractionDigits(3);
System.out.println("d:" + d);
System.out.println("a:" + f.format(d));
System.out.println("b:" + ((int)(d * 1000))/ 1000d);
 

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,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top