0

How to fix the value of a variable to two digits after the decimal point if the value coming from the database is of money data type. Also in database no precision and scale is defined for money datatype.

Ex. value from database is: 3.7700(of money datatype)

output needed: 3.77

By output i mean saving the value in a variable and printing it. Also i converted it to double and than parse it to two decimal points. But my doubt is do we have any other method which directly work on money datatype without typecasting?

4

2 に答える 2

0

Please use java.util.formatter. You can use a formatting string like "%10.2f"

于 2012-04-26T11:47:45.997 に答える
0

If the database has no precision of its own , you can use your own specifier , e.g. use System.out.println("%.2f",<money variable>); . where %.2f is used to limit the limit to 2 places after the . and f is the specifier for floating data type

From [this site][1]

[1]: http://www.drdobbs.com/jvm/184405653 i quote the following paragraph :

`The toDouble() method converts a monetary value to a double floating-point value.
However, you should avoid using the converted value for computational purposes, owing
to the problems associated with the use of floating-point data types with 
monetary data.

You can also convert a monetary value to a long integer data type (having an implied
scaling factor of 2). In this case, an automatic round-off to the nearest whole cent is
performed.`

So convert your money variable to any type with sufficient range and you can use the converted value and cast the decimals to 2 or any number of places you like.

于 2012-04-26T11:49:15.497 に答える