• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Truncating

 
M. M.
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Sheriff
Posts: 2985
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic