ivan milenkovic
ivan milenkovic

Reputation: 99

toLocaleString() changes behaviour after using toFixed method?

I was working on 'Formatting a number as price' problem on codewars and thought to have finally solved it with this code:

var numberToPrice = function(number) {
  if (typeof number !== 'number') {
    return 'NaN';
  }
  
  let newPrice = number.toLocaleString('en-US', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
}) 
  return newPrice;
}

One test failed because of rounding problem (Expected: '13,422.12', instead got: '13,422.13'), others passed.

When I changed code to this:

var numberToPrice = function(number) {
  if (typeof number !== 'number') {
    return 'NaN';
  }
  
 let price = (Math.floor(100 * number) / 100).toFixed(2);

  let newPrice = price.toLocaleString('en-US', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
}) 
  return newPrice;
}

in order to try to avoid rounding problem, to LocaleString didn't work the same. I got many errors like this: Expected: '245,123,215.00', instead got: '245123215.00'

What is going on here?

Upvotes: 1

Views: 563

Answers (1)

Nick
Nick

Reputation: 147166

Once you use toFixed, price is a string, not a number, so toLocaleString will not change it. Given that you have used Math.floor(100 * number) / 100, you have already converted price to only have two significant digits, so toFixed(2) is not necessary, and leaving price as a number allows toLocaleString to format it.

var numberToPrice = function(number) {
  if (typeof number !== 'number') {
    return 'NaN';
  }

  let price = Math.floor(100 * number) / 100;

  let newPrice = price.toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
  return newPrice;
}

console.log(numberToPrice(245123215))
console.log(numberToPrice(13422.126))

Upvotes: 1

Related Questions