2017-09-15 98 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);