File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Truncating Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Truncating" Watch "Truncating" New topic


M. M.

Joined: May 02, 2003
Posts: 1

I have been learning Java for a couple of weeks now and am stuck on how the get my final value to read 160.45 instead of 160.4519099103157...
Can you help me ....Please

Greg Charles

Joined: Oct 01, 2001
Posts: 2968

Well, there are various rounding methods in the java.lang.Math class. However, what you really want to use is a NumberFormat.

It's usually a good idea to keep this formatter separate where any class can access it. That way you can format numbers consistantly no matter where you display them.
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
You can also use a DecimalFormat:

Try replacing "0.00" with "#.00" or "#.##" to see what effects this has.
It's usually a good idea to keep this formatter separate where any class can access it.
Agreed - with the caveat that it's not thread-safe, so if you're running multiple threads you need to make sure no two threads are using the same formatter at the same time. Either protect with synchronization, or make sure each thread has its own copy of a formatter. (ThreadLocal may be useful for something like this.) This isn't anything special about NumberFormat really - if you're working with threads you should really be assuming that nothing is thread-safe unless you're guaranteed otherwise, or you've written the code to ensure thread-safety. Probably not really relevant here, but sometime in the future this may bite you if you're not careful, so I thought it worth mentioning.
[ May 03, 2003: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
M. M.,
Welcome to JavaRanch!
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.
Thanks Pardner! Hope to see you 'round the Ranch!

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Truncating
It's not a secret anymore!