0

My code in Javascript involves manipulating several variables and displaying a few of them in counters on-screen. Because of the math I'm using, I'll end up with numbers such as 1842.47167... or something similar. I want to display the number as 1,843 (rounded and with the "thousands" comma added). Does anyone have a simple and easy way to do it? See below for code I've tried.

console.log(coins) //Output: 1842.4716796875
commaCoins = coins;
commaCoins = Math.round(coins);
commaCoins = coins.toLocaleString();
console.log(commaCoins) //Output: "1,842.472"
//Desired result: 1,843

Anyone have a better way to do this?

  • Does this answer your question? [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) – balexandre Apr 25 '20 at 00:27

1 Answers1

0

You'll need to work with strings to achieve that.

Something like:

const coins = 1842.4716796875;
const roundedCoins = Math.round(coins);
const dotFormat = roundedCoins / 1000
const commaFormat = dotFormat.toString().replace('.', ',');
console.log(commaFormat) // Output: 1,842

You can obviously do that in less step and use Math.ceil() if you need to round to the upper unit.

AdMer
  • 500
  • 5
  • 17
  • Thank you! The Math.ceil() function should do the trick for me. I also found that I can put parameters into the toLocaleString to include a minimum and maximum fraction place, but this method should work better for me. – Ford Howell Apr 25 '20 at 16:02
  • Can you set this as answered ? :) – AdMer Apr 26 '20 at 00:42