Read and write buffers

When I write a float to the buffer, it does not read the same value:

> var b = new Buffer(4);
undefined
> b.fill(0)
undefined
> b.writeFloatBE(3.14159,0)
undefined
> b.readFloatBE(0)
3.141590118408203
> 
(^C again to quit)
> 

Why?

EDIT:

My working theory is that since javascript saves all numbers as double precision, it is possible that the buffer implementation does not have a null value for the remaining 4 bytes of double when it reads the float back:

> var b = new Buffer(4)
undefined
> b.fill(0)
undefined
> b.writeFloatBE(0.1,0)
undefined
> b.readFloatBE(0)
0.10000000149011612
>

I think this suggests that we have zeros for 7 digits after the decimal (well, actually, 8), and then there is trash. I think there is an error in the node buffer that reads these floats. This is what I think. This is node version 0.10.26.

+3
source share
2 answers

readFloat node ++, , / . , . , "7 " - float. 6 ( std::numeric_limits<float>::digits10), readFloatBE

+1

( "floats" ) ; , , JavaScript/NodeJS. , # float double.

. , double float:

var b = new Buffer(8);
b.fill(0);
b.writeDoubleBE(3.14159, 0);
b.readDoubleBE(0);

:

3.14159

EDIT:

, :

:

, float . , , :

var floats32 = new Float32Array(1),
    floats64 = new Float64Array(1),
    n = 3.14159;

floats32[0] = n;
floats64[0] = n;

console.log("float", floats32[0]);
console.log("double", floats64[0]);

:

float 3.141590118408203
double 3.14159

, , 7 ( ), 7 . , 7 , (3.14159 6 , 3.141590118408203 = > 7 = > 3.141590 = > 3.141590 === 3.14159).

+1

Source: https://habr.com/ru/post/1616705/