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?

Nitish
  • 834
  • 4
  • 15
  • 26
  • What do you mean by output - do you mean printing the value? – BeRecursive Apr 26 '12 at 11:44
  • 3
    What have you tried? Have you looked at http://stackoverflow.com/questions/2379221/java-currency-number-format? – radimpe Apr 26 '12 at 11:45
  • Java standard library does not defined a `Money` class so please clarify whether you are using a custom Money class or if you are interested in working with `double` values. – posdef Apr 26 '12 at 11:45
  • Do you mean storage of the value in java or just plain formatting? – mrab Apr 26 '12 at 11:47
  • 2
    **Never** use `double` or similar as a currency type! Use `BigDecimal` instead. – Anthales Apr 26 '12 at 11:49

2 Answers2

0

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

Rahul Borkar
  • 2,742
  • 3
  • 24
  • 38
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.

CyprUS
  • 4,159
  • 9
  • 48
  • 93