简体   繁体   中英

How can I sum two numbers with decimals in Javascript?

I have an exercise. there are two variables x = 4.0 and y = 4.0. Why the result is 8 and does not 8.0?

 var x = 4.0 var y = 4.0 var result = x + y console.log(result)

While these both are .0 you'd need to tell it to show the digit with: result.toFixed(1) .

Need to format your result. You can Use like below code...

var x = 4.0
var y = 4.0
var result = x + y
console.log(result.toFixed(1)) 

As JavaScript is following the international IEEE 754 standard, theoretically it has only one type of number: 64 bits double precision floating point. But in the real world, most JS engines use 32 bits Integer inside to save memory and gain more efficiency. You can use 'toFixed' to show following zero decimals but it has no meaning in a programatic way but only for representation.

You can refer to below link(an explanation from one of JS engines) http://trac.webkit.org/wiki/JavaScriptCore

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM