I try to store one float
value through Buffer
in Node.js
> f = 3.3
3.3
> var buf = new Buffer(32)
> buf.writeFloatBE(f);
4
> g = buf.readFloatBE();
3.299999952316284
Then I found the stored value g
after readFloatBE()
is NOT equal to the original f
.
After further investigation, those two buffer values stored g
and f
are same.
> var buf1 = new Buffer(4); buf1.writeFloatBE(f); buf1
<Buffer 40 53 33 33>
> var buf2 = new Buffer(4); buf2.writeFloatBE(g); buf2
<Buffer 40 53 33 33>
According to this Buffer reading and writing floats, we know the writeDoulbeBE
should be used here.
> var buf3 = new Buffer(8);
> buf3.writeDoubleBE(f);
8
> h = buf3.readDoubleBE();
3.3
> h === f
true
I want to know why the float
type is not used in Node.js
or V8
? Refer to the code from V8
// Fast primitive setters
V8_INLINE void Set(bool value);
V8_INLINE void Set(double i);
V8_INLINE void Set(int32_t i);
V8_INLINE void Set(uint32_t i);
It seems there is NO float
type in V8
, any reason of this design or am I missing something? In which case, should this function writeFloatBE()
be used?
Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.
There are also separate data types that you can use to store numbers with fractional part — 'float' which takes up 4 bytes and 'double' with 8 bytes.
Check if the value has a type of number and is not an integer. Check if the value is not NaN . If a value is a number, is not NaN and is not an integer, then it's a float.
It seems there is NO
float
type in V8
Yes, and this is by design: There is no float
type in JavaScript either. All numbers are double
s as specified by the ECMAScript standard.
Your number f
is therefore 3.3
with double
precision, while g
only has float
precision. As you can see, that's not the same double as f
. The same would happen if you used one of the buf.writeInt…
methods, the result after reading it would only be 3
not 3.3
.
In which case, should the function
writeFloatBE()
be used?
Yes, of course it should be used, whenever you want to store numbers with float
precision in a buffer. If you want to store f
with full precision, use writeDoubleBE
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With