Reputation: 2615
This is both a PHP and JS question.
I'm getting bunch of prices from an API that returns them as strings.
"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.
"62.50" => 62.50 "16.67" => 16.67 "150.00" => 150
Then what I'll do is, using JS, include the currency.
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
Any thoughts?
Upvotes: 0
Views: 177
Reputation: 2510
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)
Upvotes: 0
Reputation: 151
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
and this will make it work
Upvotes: 1