0

Working on a Node web app with a MongoDB backend that consists of player statistics. In this specific instance, I'm saving a player stat as a decimal and converting it to a percentage on the webpage by multiplying the value by 100.

Here's the HTML / EJS template code I render on the page for a players 3 point percentage from one season:

<td><%= season.tp * 100 %></td>

Pass in that value and multiply it for a percentage that should be (for example) 39.8 and that is the case for most statistics; however, for one data point in particular it's 39.80000000004. This leads me to two questions:

  1. What could cause the number to format with these excessive (and nonexistent) decimal places? Is this something to do with how MongoDB stores number data?
  2. What can I do to prevent these decimal places from displaying?

I've seen other questions where the proposed solution is a JavaScript method that formats the decimal places, but changes the data type to a String. Since the goal would be to perform other aggregations with this data, I'd want to preserve the number type.

Thanks in advance for the help.

Franchise
  • 1,081
  • 3
  • 15
  • 30
  • 1
    IEEE754 arithmetic is not "precise". For example `0.398 * 100 === 39.8` yields false. – Yury Tarabanko May 06 '20 at 15:09
  • Does this answer your question? [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – Yury Tarabanko May 06 '20 at 15:09
  • @YuryTarabanko - that's all great background information that I was not aware of, as this is my first real foray into a web app that's backed with a NoSQL DB. Is there a native JS method I can use to trim the decimals? – Franchise May 06 '20 at 15:17
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Number/toPrecision https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed – Yury Tarabanko May 06 '20 at 15:20

1 Answers1

0

With help from @YuryTarabanko in the comments above, I've come up with a solution that suits my needs for now:

<td><%= (season.tp * 100).toFixed(1) %></td>

This toFixed() method ensures that all numbers passed through to the app from the DB are rounded to one decimal point. It should be noted that these values are now strings, rather than numbers. Hope this helps someone in the future.

Franchise
  • 1,081
  • 3
  • 15
  • 30