aspose file tools*
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


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Truncating" Watch "Truncating" New topic
Author

Truncating

M. M.
Greenhorn

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


Newbie
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2864
    
  11

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
Wanderer
Sheriff

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
Sheriff

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: http://aspose.com/file-tools
 
subject: Truncating