+ 1

Float/double data

var x = 4.0; var y = 4.0; console.log(x + y); Why the output giving me 8 instead of 8.0

21st Aug 2024, 11:55 AM
Christopher Sikombe
Christopher Sikombe - avatar
4 Answers
+ 2
let x = 4.0; let y = 4.0; console.log(x); console.log(y); console.log(x.toFixed(1)); console.log(y.toFixed(1)); console.log(x + y); console.log((x + y).toFixed(1));
21st Aug 2024, 12:41 PM
Bob_Li
Bob_Li - avatar
+ 1
Don't think in terms of integers and floats. Javascript have Number. It is actually a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. Why it doesn't display decimal values when the decimal value is .0 is probably a default behavior to keep the value as a fake 'integer' if there is no fractional value. Basically, if a double does not have a fractional value, it is an 'integer' in Javascript. So 4.0 is an integer in Javascript. let n = 4.0; console.log(Number.isInteger(n));//true ?! n = 4.00001; console.log(Number.isInteger(n));//false There is no 'should be'. Every language have their own design choices, however quirky it might be. It is a language design decision by the Javascript creator. You have to explicitly ask the language to display the extra .0 if you want it. Javascript is full of these quirky design choices. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
21st Aug 2024, 2:31 PM
Bob_Li
Bob_Li - avatar
0
Maybe it's better to ask the creator of JavaScript!
21st Aug 2024, 12:31 PM
Jan
Jan - avatar
0
Bob_Li But it's still a little bit weird that it outputs as an integer when toFixed is not used. Basically it should output 8.0
21st Aug 2024, 1:01 PM
Jan
Jan - avatar