2016-07-19 80 views
1

我有這個直接的JavaScript函數,它使用d3-format將字符串和貨幣代碼轉換爲格式化數字。d3格式的數字不顯示千位分隔符

import * as d3Format from 'd3-format'; 
import d3 from 'd3'; 

export const toCurrency = (number, currencyCode) => { 
    const formatDef = { 
    "decimal": ".", 
    "thousands": ",", 
    "grouping": [3], 
    "currency": [convertCodeToSymbol(currencyCode), ""]}; 
    const locale = d3Format.formatLocale(formatDef); 
    return locale.format("($.2f")(number); 
}; 

const convertCodeToSymbol = (currencyCode) => { 
    const conversions = { 
     "USD": "$", 
     "EUR": "€", 
     "GBP": "£" 
    }; 
    return conversions[currencyCode] ? conversions[currencyCode] : currencyCode; 
}; 

它的工作原理除了不顯示千位分隔符外。鑑於(1999,「美元」)它返回「1999.00美元」。我已經對文檔進行了雙重檢查,但數千和分組屬性看起來都是正確的。我正試圖獲得「$ 1,999.00」。

(注意,進口D3線是沒有必要的,但我把它只是爲了確保我不缺少庫的一部分。我已經安裝了D3和D3-格式NPM)

回答

3

通過提供locale definitionthousands屬性,您只能指定組分隔符看起來像,就像請求格式化時一樣。要真正組格式化輸出,你需要包含逗號(,)選擇到提供給locale.format(specifier)的符串:

逗號(,)選項允許使用一組分離,如數千個逗號。

爲您的代碼,這意味着改變符串

return locale.format("($,.2f")(number); 

應該做的伎倆。

此工作示例顯示了差異:

console.log(d3.format(".2f")(1999)); // 1999.00 
 
console.log(d3.format(",.2f")(1999)); // 1,999.00
<script src="https://d3js.org/d3.v4.js"></script>

+0

啊,當然。現在我的測試通過了,謝謝! – Mike