This week's book giveaway is in the Performance forum.We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!

# Round to the nearest 10th?

Jerome Butler
Greenhorn
Posts: 2
I am using Java 5 on WinXP...

How do I round the following to the nearest tenth?

I tried Math.round() but it didn't work...

Here's my code:

How can I make it display 10.50?

Thanks,

Jerome

Jesus Angeles
Ranch Hand
Posts: 2068

double value = 10.499

System.out.println((Math.round(value*10))/10);

Garrett Rowe
Ranch Hand
Posts: 1296
You could try the java.text.DecimalFormat class:

Output:

Scott Selikoff
author
Saloon Keeper
Posts: 4015
18
Math.round() converts from double to long, and from float to int, as an alternate to casting (which always truncates).

The suggestion to use DecimalFormat is an excellant one. For anything having to do with displaying data to the user, it makes sense since it converts the number into a string. The only time i wouldn't use it is if you need the numeric value of the converted number for an math-based algorithm. You could still use DecimalFormat but converting to string then back to a number is extra work.
[ February 04, 2006: Message edited by: Scott Selikoff ]

Ranch Hand
Posts: 95
Originally posted by Jerome Butler:
I am using Java 5 on WinXP...

How do I round the following to the nearest tenth?

I tried Math.round() but it didn't work...

Here's my code:

How can I make it display 10.50?

Maybe that was just a typo, but 10.50 is the nearest hundredth, not the nearest tenth. (10.5)

Jim Yingst
Wanderer
Sheriff
Posts: 18671
Using JDK 5, you can use

or

depending on whether you really want tenths or hundreds. See here for more info.
[ February 04, 2006: Message edited by: Jim Yingst ]

Jerome Butler
Greenhorn
Posts: 2
Jim, Jesus, and others,

Thanks for the cool suggestions...

What about when it comes to trying to round to the nearest .05?

Should I do it like this:

Hope to hear a response,

Ranch Hand
Posts: 95
Originally posted by Jerome Butler:
Jim, Jesus, and others,

Thanks for the cool suggestions...

What about when it comes to trying to round to the nearest .05?

Should I do it like this?

This won't work. Math.round(double) rounds double to the nearest long. multiplying by .05 is equivalent to dividing by twenty. Quick calculations suggest, then that any
I'll track the steps in this algorithm with a range of values:
values from -10 to 9
*.05 -.5 to .45
Math.round 0 to 0
/.05 0 to 0
So anything between -10 and 9.9999 will be mapped to 0.

You want things to go to the nearest .05 - here's how one might go to the nearest .5.

Math.round(value * 2) /2

Now let's trace a few values:

I haven't checked whether it works for 1.5 itself, and you will need to make it apply to your situation a little more directly.

HTH