-1

(UPDATE: To all those saying this is a dupe and voting to close, it is not a dupe of this question: the difference is that I want to display 1 dp numbers to 2 dp. It may well be a dupe of some other question, but please post a link if it is!)

I want to display a price in JavaScript. I would like to display an integer if the original number is a whole number. Or if it's a float, I would like to display it rounded to two decimal places.

input  |  output
24     |  24
24.231 |  24.23
24.2   |  24.20

I've tried Math.round(num * 100) / 100, but that doesn't convert 24.2 correctly.

I've also tried .toFixed(2) but that converts 24 to 24.00, which isn't what I want.

Any ideas? This must be a very common problem when displaying prices.

Richard
  • 62,943
  • 126
  • 334
  • 542
  • 5
    It's more common to always have the .00, even for whole number prices – EKW Jan 22 '18 at 10:48
  • Check if it's a [whole number](https://stackoverflow.com/questions/3885817/how-do-i-check-that-a-number-is-float-or-integer) then use `tofixed` if it's not. – Liam Jan 22 '18 at 10:49
  • Possible duplicate of [Round to at most 2 decimal places (only if necessary)](https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary) – Rajesh Jan 22 '18 at 10:57
  • @Rajesh it's not a duplicate of that qu - I want to show two dp for numbers with one dp. Have updated question to make clear. – Richard Jan 22 '18 at 11:05
  • @EKW thanks, but that's not what I'm looking for. – Richard Jan 22 '18 at 11:05
  • @Richard If you see the selected answer, it does what you need. https://stackoverflow.com/a/11832950/3783478 – Rajesh Jan 22 '18 at 11:08
  • @Rajesh that's not correct, sorry. Have you tried `Math.round(24.2 * 100) / 100`? It gives `24.2`, not `24.20`. – Richard Jan 22 '18 at 11:10

2 Answers2

1

You're probably gonna need to use an if statement for this.

if(Number.isInteger(price)) {
    return price;
} else {
    return price.toFixed(2);
}
EKW
  • 2,059
  • 14
  • 24
1

You need to check if the number is whole, if so then convert to a string without decimals, else convert to a string with 2 decimals.

console.log(displayRounded(23.237));
console.log(displayRounded(23.231));
console.log(displayRounded(24.2));
console.log(displayRounded(24));

function displayRounded(price) {
  return Number.isInteger(price) ? price.toString() : price.toFixed(2);
}
Peter B
  • 22,460
  • 5
  • 32
  • 69