It's not a secret anymore!*
The moose likes Beginning Java and the fly likes need a double returned with 2 decimal points Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "need a double returned with 2 decimal points" Watch "need a double returned with 2 decimal points" New topic
Author

need a double returned with 2 decimal points

AnilPrakash Raju
Ranch Hand

Joined: Jul 26, 2004
Posts: 137
Hi,

I need to return a double value with two decimal points ( even if the last decimal value = 0) I have used numberFormat but returns a string and when I convert the string back to double i lose the last decimal vale if equal to 0.

eg from numberFormat i get a string with value 23.30, and when i convert it to double, it gives 23.3

any suggestions will be greatly appreciated.

Thanks

Anil
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37900
    
  22
A double doesn't have any number of decimal points. You can try rounding it to 2dp precision, which is as near as you will get. There is the Math.round() method, but you will have to multiply and divide to use that.
You can use several methods, one of which you have already found, to display it with 2dp.
AnilPrakash Raju
Ranch Hand

Joined: Jul 26, 2004
Posts: 137
Thanks Campbell,

I do round it off to 2 decimal points, but if the last digit is 0, i get only decimal point.

Anil
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18500
    
  40

Originally posted by AnilPrakash Raju:
Thanks Campbell,

I do round it off to 2 decimal points, but if the last digit is 0, i get only decimal point.

Anil



No... You don't get only 1 decimal point. You don't get any number of decimal points. There is *no* formatting to a double. Period.

The only time that you "get" a number of decimal points, is when you print it out (output of the program). In this regard, what is wrong with using NumberFormat? So, it's a string? You are only going to print it out anyway. Use NumberFormat to help with outputing the result -- and leave your double alone.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
AnilPrakash Raju
Ranch Hand

Joined: Jul 26, 2004
Posts: 137
Thanks Henry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: need a double returned with 2 decimal points
 
Similar Threads
double
Decimals not converting to correct fractions
Convert String into double?
Trouble with BigDecimal and Double
how to convert double as a currency