2017-09-15 45 views
0

我很納悶,同時保持了2位小數如何有效地從價格移除小數零,如果有的toLocaleString價無小數點零

因此,如果價格是135.00它應該成爲135

如果價格是135.30但是它應該保留兩位小數。

如果價格是135.38它可以保留小數。

這是我的時刻:

const currency = 'EUR'; 
const language = 'NL'; 

var localePrice = (amount) => { 
    const options = { 
    style: 'currency', 
    currency: currency 
    }; 

    return amount.toLocaleString(language, options); 
} 

現在我可以使用正則表達式或類似的東西,但我希望有得到這個工作更簡單的方法。

我做了一個JSFiddle,它說明了我的問題,它可以很容易地使用代碼。

https://jsfiddle.net/u27a0r2h/2/

回答

1

你可以添加一個功能檢查,如果數字是整數或不和使用您的localePrice函數內的條件以應用格式(與片打去除十進制):

function isInt(n) { 
    return n % 1 === 0; 
} 

const currency = 'EUR'; 
const language = 'NL'; 


var localePrice = (amount) => { 
    const options = { 
    style: 'currency', 
    currency: currency 
    }; 

    if (isInt(amount)){ 
    return amount.toLocaleString(language, options).slice(0, -3); 
    } 
    else { 
    return amount.toLocaleString(language, options); 
    } 
} 

document.querySelector('.price').innerHTML = localePrice(135.21); 

document.querySelector('.price-zeroes').innerHTML = localePrice(135.00); 

document.querySelector('.price-with-one-zero').innerHTML = localePrice(135.30);