2010-02-12 100 views
57

我想將3.50存儲到mysql表中。我有一個可以存儲的浮點數,但它存儲爲3.5,而不是3.50。我怎樣才能得到它的尾部零點?在mysql中存儲金額

回答

89

錢值不存儲爲浮動,使用十進制或數字類型:

Documentation for MySQL Numeric Types

編輯&澄清:

浮點值易受舍入誤差他們只有有限的精度所以,除非你不關心你只能得到9.99而不是10.00,你應該使用DECIMAL/NUMERIC,因爲它們是沒有這種問題的定點數。

18

它真的很重要,如果它存儲爲3.5,3.50甚至3.500?

真正重要的是它從數據庫中檢索後的顯示方式。

或者我在這裏錯過了什麼?

也不要使用浮點數,使用小數。浮動有各種各樣的舍入問題,並不是很大。

+1

我確實提到了四捨五入問題。我的觀點是他不應該擔心它是如何存儲的,而是如何顯示的。您不會將財務信息存儲到小數點後兩位 - 匯率爲5,我們存儲爲6,但只顯示爲2. – 2014-09-04 07:51:14

+1

(刪除以前無關的評論)。舍入爲好點+1。 – 2014-09-04 18:36:23

4

爲什麼要將「3.50」存儲到數據庫中?就數據庫而言,3.5 == 3.50 == 3.5000。

您的演示文稿和格式的數字/日期/等應在應用程序,而不是數據庫中完成。

5

如果使用DECIMAL或NUMERIC類型,可以將它們聲明爲例如DECIMAL(18,2),即使它們爲0,也會強制2位小數。根據期望的值有多大,可以更改第一個參數。

16

存儲值可以使用DECIMAL(10,2)場,然後你可以使用FORMAT功能:

SELECT FORMAT(`price`, 2) FROM `table` WHERE 1 = 1 
35

這不是一般將錢存爲一個浮動一個好主意,因爲四捨五入計算中可能會發生錯誤。

請考慮使用DECIMAL(10,2)。

+1

無論精度如何,甚至像0.1和0.2這樣的數字都不可能用二進制浮點表示。 http://en.wikipedia。組織/維基/ Floating_point – Ray 2014-12-21 21:56:35

0

二進制不能準確地表示只有有限位數的浮點數。這不是數據,以便muuch損失,但實際上轉換錯誤.. Here's the manual giving examples

你可以在瀏覽器中看到這個動作,看到自己在這個代碼片斷。

<script> 
 

 
    var floatSum = 0; 
 

 
    // add 0.1 to floatSum 10 times 
 
    for (var i=0; i<10; i++) { 
 
     floatSum += 0.1; 
 
    } 
 

 
    // if the repetative adding was correct, the floatSum should be equal to 1 
 
    var expectedSum = 10*0.1; // 1 
 

 
    // you can see that floatSum does not equal 1 because of floating point error 
 
    document.write(expectedSum + " == " + floatSum + " = " + (expectedSum==floatSum) + "<br />"); 
 

 

 
    // --- using integers instead --- 
 
    // Assume the example above is adding £0.10 ten times to make £1.00 
 
    // With integers, we will use store money in pence (100 pence (also written 100p) in £1) 
 

 
    var intSum = 0; 
 

 
    // add 0.1 to floatSum 10 times 
 
    for (var i=0; i<10; i++) { 
 
     intSum += 10; 
 
    } 
 

 
    // if the repetative adding was correct, the floatSum should be equal to 1 
 
    var expectedSum = 10*10; // 100 
 

 
    // you can see that floatSum does not equal 1 because of floating point error 
 
    document.write(expectedSum + " == " + intSum + " = " + (expectedSum==intSum) + "<br />"); 
 
    document.write("To display as &pound; instead of pence, we can divide by 100 (presentation only) : &pound;" + intSum/100 + "<br />"); 
 
</script>