5

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?

Community
  • 1
  • 1
zangw
  • 43,869
  • 19
  • 177
  • 214

1 Answers1

6

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 doubles 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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375