0

About toFixed() in JS

I met with a challenge question like this: let sum = 0.1 + 0.2; console.log(+sum.toFixed(2)); The answer is 0.3. Why? I thought it should be 0.30. - Confused Boy

16th Apr 2019, 2:29 PM
Zhiming Li
Zhiming Li - avatar
2 Answers
+ 3
Typecasted back into Number due to the plus operator before sum. https://code.sololearn.com/W8ZgKlTH97cJ/?ref=app ę›äø€å€‹čŖŖę³•ļ¼š å¦‚ęžœåŖęœ‰ sum.toFixed(2)ļ¼Œēµęžœę˜Æ 0.30ļ¼Œå› ē‚ŗę˜ÆString怂 ä½†ē¾åœØęœ‰ ļ¼‹č™ŸåœØå‰é¢ļ¼Œé€™å€‹ ļ¼‹č™Ÿå› ē‚ŗå‰ę–¹ē„”Stringļ¼Œč€Œå¾Œę–¹åÆä»„parseFloat()ļ¼Œę‰€ä»„č¢«åˆ¤å®šē‚ŗ Number.prototype.addition() ļ¼Œč€Œäøę˜ÆString.prototype.concantentation()。因此 0.30č¢«č½‰åŒ–å›žNumberļ¼Œč€Œå°ę•øé»žäŗŒä½ēš„0äøę˜Æ significant figureļ¼Œę‰€ä»„åœØéŽēØ‹äø­č¢«ęØåŽ»äŗ†ć€‚
17th Apr 2019, 10:42 AM
Gordon
Gordon - avatar
0
Gordon č°¢č°¢šŸ™‚
19th Apr 2019, 11:43 AM
Zhiming Li
Zhiming Li - avatar