2012-04-26 124 views
0

如果來自數據庫的值是貨幣數據類型,如何在小數點後將變量的值修復爲兩位數。 同樣在數據庫中,沒有爲貨幣數據類型定義精度和小數位數。如何使用money數據類型?

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

output needed: 3.77 

通過輸出我的意思是將值保存在變量中並打印出來。我也將它轉換爲double,並將其解析爲兩個小數點。但是我的疑問是,我們有沒有其他方法可以直接處理money數據類型而不用類型轉換?

+0

你是什麼意思的輸出 - 你的意思是打印的價值? – BeRecursive 2012-04-26 11:44:45

+3

你有什麼嘗試?你看過http://stackoverflow.com/questions/2379221/java-currency-number-format? – radimpe 2012-04-26 11:45:38

+0

Java標準庫沒有定義'Money'類,所以請說明您是使用定製的Money類,還是有興趣使用'double'值。 – posdef 2012-04-26 11:45:50

回答

0

如果數據庫沒有自己的精度,則可以使用自己的說明符,例如,使用System.out.println("%.2f",<money variable>);。其中%.2f使用.f後以限制限制至2位是浮動的數據類型

在[這個網站]的說明符[1]

[1]:http://www.drdobbs.com/jvm/184405653我引用以下內容:

`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.` 

所以你的錢變量轉換爲任何類型的足夠的範圍,你可以使用轉換後的值,並投了小數2或任意數量的你喜歡的地方。

0

請使用java.util.formatter。您可以使用格式化字符串,如「%10.2f」

+0

不建議使用float/double數據類型。 – mrab 2012-04-26 11:49:32

相關問題