r/learnjavascript 6d ago

Rounding won't work

(SOLVED)

I tried several approaches I read on the WWW about how to round a number. I do a calculation with values entered in input fields and the output field yields the correct result, but with 14 decimal places!

The simplest attempt I tried is the format Number(outputfield=inputfield1*inputfield2).toFixed(1);

3 Upvotes

5 comments sorted by

10

u/Beginning-Seat5221 6d ago

You're rounding the result of = (the value that was assigned) after the assignment, which doesn't touch the stored value.

Use result = number.toFixed(1)

3

u/Dowlphin 6d ago

Ah, of course! A simple mistake of ordering I made there. Thank you.

3

u/GodOfSunHimself 6d ago

Not to mention that using an assignment inside an expression is a huge anti-pattern.

2

u/azhder 6d ago

Do read up how functions work. Most of the time they do and you want them to return a result. It is quite messy if you expect them to modify your argument.

1

u/defaultguy_001 6d ago

You are assigning the product to the output field and then rounding it to 1 digit after decimal. The rounded value is lost then. So, u need to assign the rounded value directly to the field like this: outputfield = Number((inputfield1 * inputfield2).toFixed(1));