0

I want to round up the result of this to 2 decimal places. I already tried Math.floor*(Math.pow (1.02,7)*100)/100 But I get 1,150 instead of 1,148.69 - the answer I aim to be returned.

A snippet of my code atm:

function money (amount) {

  return amount*(Math.pow (1.02,7))
}

money(1000);
JSNoob
  • 5
  • 2
  • This may be a duplicate question. [Check the answers here](https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary) – Yuran Pereira Aug 14 '20 at 00:01
  • `Number.toFixed(2)` is what you need. Take note that a String is returned. – StackSlave Aug 14 '20 at 00:06
  • "*I get 1,150 instead of 1,148.69*" - I cannot reproduce.`Math.floor(Math.pow (1.02,7)*100)/100` does return the expected `1.14` for me. Notice that `1.14869` has 5 decimal places not just 2. – Bergi Aug 14 '20 at 00:11

3 Answers3

3

You can use toFixed to round to a certain decimal

function money (amount) {

  return (amount*(Math.pow (1.02,7))).toFixed(2)
}

console.log(money(1000))
Lex
  • 4,749
  • 3
  • 45
  • 66
1
function money (amount) {
    return  Math.round(((amount*(Math.pow (1.02,7))) * 100)) / 100;
}
console.log(money(1000));

This will give the

Darth Vader
  • 881
  • 2
  • 7
  • 24
0

Here is how .toFixed() is used:

function money(amount){
  return (amount*Math.pow(1.02, 7)).toFixed(2);
}
console.log(money(1000));
StackSlave
  • 10,613
  • 2
  • 18
  • 35