In this video, you rounded one pack total two ways and found out which result you can keep calculating with.
Key Points
- Two ways to round:
Math.round(totalKg * 100) / 100rounds a total to two decimals and gives back a number.totalKg.toFixed(2)also rounds it to two decimals, keeping the zero at the end, and gives back a string. - Calling
toFixed(): You write it after the number’s name with a dot in between, and put the number of decimals you want inside the parentheses. - Check the type: The quotes around
'4.10'show that it’s text.typeof shownKggives'string', whiletypeof roundedKggives'number'. +joins text: Adding0.5to the number4.1gives4.6. Adding0.5to the string'4.10'gives'4.100.5', because when one side of+is a string,+joins the two values, the same way"5" + 2gives'52'.- Keep the number, show the text: Keep your totals as numbers while you calculate, and call
toFixed()only at the moment you show one.
In the REPL
> const totalKg = 2.2 + 1.1 + 0.8
undefined
> totalKg
4.1000000000000005
> const roundedKg = Math.round(totalKg * 100) / 100
undefined
> roundedKg
4.1
> const shownKg = totalKg.toFixed(2)
undefined
> shownKg
'4.10'
> typeof shownKg
'string'
> typeof roundedKg
'number'
> roundedKg + 0.5
4.6
> shownKg + 0.5
'4.100.5'