parseFloat question

I am trying to shorten the decimals when i am given the return of a number. I have two inputs that result in a number, but i am not sure how to implement it so it shorten the decimal points. For example 1.11111 becomes 1.11

I have tried to use Math.round as well but not having any luck

$('.field5').val($('.field4').val() / $('.field3').val());

no worries friends, solved it.

$('.field5').val(Math.round($('.field4').val() / $('.field3').val() * 100) / 100)

parseFloat may help, but you may want to use toFixed(). Personally, I use them both.

let percentVal = $('.field5').val($('.field4').val() / $('.field3').val());
let trimmedVal = percentVal.toFixed(3);
let finalVal = parseFloat(trimmedVal)

the first line is your calculation, the second line is the trimmed value, and the third line removes any trailing zeros, simply for cosmetic effect.

1 Like

is there a benefit to using one over the other?

one which, your use of Math.round() versus mine of toFixed()? not much difference, really. Using toFixed() does round the number to the given precision, while using Math.round, you are multiplying by 100, rounding as an integer, and then dividing by 100. Not wrong, simply an extra step.

parseFloat(), however, is another animal entirely. It takes a string and converts it to a floating-point number. If passed a number, it converts it to a string, then converts it BACK to a number. In your case, may be redundant.

Where I found parseFloat handy in this sense, was when building a calculator. It removes the trailing zeroes that may get left behind if i use toFixed(8) to set a higher precision.


great to know, thanks again!!

toString returns a string and Math.round returns a number. Depending out what you are doing with the value later, could determine which one to choose.

1 Like

thanks for the insight!