0

In my MongoDB/Node backend I am doing some totaling of dollar amounts and returning that data to the front end. Note this is for displaying totals only, we're not altering the values themselves. Because we want two decimal places for the totaled dollar values, I am doing this:

let roundedTotalOpenBalance = math.round(totalOpenBalance, 2);

That will give me something like -- 322.45 -- which is what I want.

However, if the value total is 322, I'd like to also pass that to the front end as 322.00. How can I do this with math js? Or do I need to handle the transformation myself?

Muirik
  • 6,049
  • 7
  • 58
  • 116
  • why not just add it in during the front end if youre going to display it there. Once the value becomes a string it's trivial to concatenate ".00" if it's an integer – Matthew Ciaramitaro Aug 06 '18 at 15:08
  • Because we've decided we want to hand it to the front-end with this already done. Team decision. – Muirik Aug 06 '18 at 15:09
  • 2
    https://stackoverflow.com/a/2433188/2055998 – PM 77-1 Aug 06 '18 at 15:09
  • @Muirik `toFixed` -> `returns a string representing the given number using fixed-point notation` – A l w a y s S u n n y Aug 06 '18 at 16:04
  • And if wrap that in parseFloat() I'm back where I started. Is there no simple way to handle this WITHOUT converting to a string? – Muirik Aug 06 '18 at 16:06
  • You don't need to use math.js. Javascript handles this fine without any external libraries. The answer you accepted is basically the same as the accepted answer on the other question. I would expect this question to get closed eventually anyway – Liam Aug 06 '18 at 16:14

2 Answers2

2

Discard Math.round() and Try with toFixed()

let num1 = 322.45;
let roundedTotalOpenBalance1 = num1.toFixed(2);
console.log(roundedTotalOpenBalance1);

let num2 = 322;
let roundedTotalOpenBalance2 = num2.toFixed(2);
console.log(roundedTotalOpenBalance2);
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • Thanks. I am looking for a solution, ideally, that doesn't convert the value to a string the way toFixed() does. – Muirik Aug 06 '18 at 16:29
1

roundedTotalOpenBalance.toFixed(2) should do the trick :)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

Maciej Wojsław
  • 403
  • 2
  • 10