+ 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
4 odpowiedzi
+ 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));
+ 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
0
Maybe it's better to ask the creator of JavaScript!
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