1

Here's the code below:

let moneyToReturn = 0.5
let note = 0.01
let sum = 0

while(moneyToReturn-note>=0){ 

    moneyToReturn = ((moneyToReturn*10 - note*10)/10).toFixed(2)
    sum = ((sum*10 + note*10)/10).toFixed(2)

//  moneyToReturn -= note
//  sum += note

    console.log(sum)
}

To make sure that I'm not logging my sum with crazy decimal places on each computation I need to write this code.

((x * 10 + y * 10)/10).toFixed(2)

What is the better/shorter way of doing that?

karolis2017
  • 2,195
  • 8
  • 24
  • 49
  • You could define a function that accepts an integer (cents) which then divides the parameter by 100 and returns the .toFixed(2) value so it's more reusable. – WOUNDEDStevenJones Sep 18 '18 at 00:18

1 Answers1

0

Perhaps you could use parseFloat to avoid then need for your arithmetic like so?

while(moneyToReturn-note>=0){ 

    moneyToReturn = parseFloat((moneyToReturn - note).toFixed(2))
    sum = parseFloat((sum + note).toFixed(2))

//  moneyToReturn -= note
//  sum += note

    console.log(sum)
}

You should find that the use of parseFloat as shown above is functionally equivalent to ((x * 10 + y * 10)/10).toFixed(2) as the following code sample shows:

var x = 0.1
var y = 0.3

console.log('Current method', ((x * 10 + y * 10)/10).toFixed(2) )
console.log('Concise method', (parseFloat(x + y).toFixed(2)) )
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
  • 1
    Thanks. Your solutions look a little better. Now I'm pondering that dealing with numbers in javascript is quite complicated and you really need to be careful especially if high precision is needed. – karolis2017 Sep 18 '18 at 00:26
  • 1
    Beware. When I worked as a programmer in the financial industry, we _never_ used floating point arithmetic because of the accrued rounding errors. You'd base money on fixed fractions of a cent, say 1-100th of a cent, and use _decimal_ math (like Java's BigDecimal class) — see this SO question: [BigDecimal in JavaScript](https://stackoverflow.com/q/16742578/17300) – Stephen P Sep 18 '18 at 00:37