[英]Converting string to number with decimal places if the number isn't whole
This is both a PHP and JS question.这既是 PHP 和 JS 问题。
I'm getting bunch of prices from an API that returns them as strings.我从 API 那里得到一堆价格,它以字符串的形式返回。
"62.50", "16.67", "150.00" “62.50”、“16.67”、“150.00”
What I need to do is, using PHP, convert these into a) a number/int if the numbers after decimal points are 00 and b) keep the 0 where it's one single decimal 0.我需要做的是,使用 PHP,将它们转换为 a)如果小数点后的数字是 00,则将其转换为数字/整数,并且 b)将 0 保留为一个小数点 0。
"62.50" => 62.50 "16.67" => 16.67 "150.00" => 150 “62.50” => 62.50 “16.67” => 16.67 “150.00” => 150
Then what I'll do is, using JS, include the currency.然后我要做的是,使用 JS,包括货币。
addCurrency: function(price, currencyCode) {
return parseFloat(price).toLocaleString(navigator.language, {
style: 'currency', currency: currencyCode, minimumFractionDigits: 0, maximumFractionDigits: 2
});
}
I've tried so many variations with the price floatvar
, (float)
etc but the only issue is "62.50" becomes 62.5我已经尝试了很多价格floatvar
、 (float)
等的变化,但唯一的问题是“62.50”变成了 62.5
Any thoughts?有什么想法吗?
addCurrency: function(price, currencyCode) {
return parseFloat(price).toLocaleString(navigator.language, {
style: 'currency', currency: currencyCode, minimumFractionDigits: Number.isInteger(parseFloat(price)) ? 0 : 2, maximumFractionDigits: 2
});
}
Set the minimumFractionDigits
to Number.isInteger(parseFloat(price))? 0: 2
将minimumFractionDigits
设置为Number.isInteger(parseFloat(price))? 0: 2
Number.isInteger(parseFloat(price))? 0: 2
and this will make it work Number.isInteger(parseFloat(price))? 0: 2
,这将使它工作
custom modifier You can try it自定义修饰符你可以试试
const result = ['62.50', '150.00'].map(el => { if(el.split('.')[1] === '00') { return el.split('.')[0] } return el; }) console.log(result)
Returns number:返回号码:
const result = ['62.50', '150.00'].map(el => {
if(el.split('.')[1] === '00') {
return Number(el.split('.')[0])
}
return Number(el);
})
console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.