Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Decimal Rounding Without Function

Sometimes when math happens in javascript it makes like a really long decimal and Math.floor() only rounds to the nearest integer. I wanna be able to round to a certain amount of decimal points without having to make a function.

I ran this:

const prompt = require('prompt-sync')();

var bp = 1.69
var fp = 1.09
var sp = 0.99

var nob = prompt("How many burgers would you like? ");
var nof = prompt("How many fries do you want? ");
var nos = prompt("How many sodas do you desire? ");
var sub = nob * bp + fp * nof + sp * nos
console.log("Your subtotal is: " + sub); 
var tax = sub * 0.065
console.log("Your tax is: " + tax)
console.log("Your total is: " + (sub + tax))

I inputted 2 for each, 2 burgers, 2 fries, 2 sodas.
I expected to get subtotal of 7.54. Instead, I got a subtotal of 7.540000000000001

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is the expected behaviour. To get your expected you want to remove all unnecessary decimals

console.log("Your total is: " + (sub + tax).toFixed(2))

This will give you the expected result.

toFixed take an argument that is the amount of decimals you want.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading