Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
¿Por qué obtengo más decimales de la resta?

estaba haciendo una pregunta de algoritmo, y mi código produjo un resultado inesperado. aquí está el código

 const price = 3.26; const cash = 100; const cid = [ ["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100] ]; function checkCashRegister(price, cash, cid) { let change = cash - price; let totalInReg = 0; for (let i = 0; i < cid.length; i++) { totalInReg += cid[i][1]; } if (totalInReg < change) { const output = { status: "INSUFFICIENT_FUNDS", change: [] }; console.log(output); } const coins = { 'PENNY': 0.01, 'NICKEL': 0.05, 'DIME': 0.1, 'QUARTER': 0.25, 'ONE': 1, 'FIVE': 5, 'TEN': 10, 'TWENTY': 20, 'ONE HUNDRED': 100 } const outputArr = []; for (let i = cid.length - 1; i >= 0; i--) { const coinType = cid[i][0]; let coinReg = cid[i][1]; const coinValue = coins[coinType]; const infoArr = []; if (coins[coinType] > change) continue; let currCoinCt = 0; do { coinReg -= coinValue; change -= coinValue; /* change = parseFloat(change.toPrecision(4)); */ console.log(change) currCoinCt++; } while (coinReg > 0 && change >= coinValue) infoArr.push(coinType); infoArr.push(currCoinCt * coinValue); outputArr.push(infoArr); } }

esperaba que restara los valores de las monedas, que solo tenían 2 decimales como máximo. pero el resultado que obtengo en la consola es:

 76.74 56.739999999999995 36.739999999999995 26.739999999999995 16.739999999999995 11.739999999999995 6.739999999999995 1.7399999999999949 0.7399999999999949 0.4899999999999949 0.23999999999999488 0.13999999999999488 0.03999999999999487 0.02999999999999487 0.01999999999999487 0.009999999999994869

con el uso de toPrecision y parseFloat, pude remediar mi problema. ¿Pero por qué sucede esto? ¿Es esto una cosa de javascript? Estoy usando un editor en línea en 'jsfiddle.net'. gracias de antemano

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!