programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

need a double returned with 2 decimal points

AnilPrakash Raju
Ranch Hand
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
Marshal
Posts: 56533
172
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
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
Posts: 23295
125
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

AnilPrakash Raju
Ranch Hand
Posts: 137
Thanks Henry