简体   繁体   中英

Converting string to number with decimal places if the number isn't whole

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?

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 Number.isInteger(parseFloat(price))? 0: 2 and this will make it work

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM