javascript float from/to bits

后端 未结 5 1101
孤独总比滥情好
孤独总比滥情好 2020-12-01 09:50

I am trying to perform something that is brain-dead simple in any other language but not javascript: get the bits out of float (and the other way around).

In C/C++ i

5条回答
  •  星月不相逢
    2020-12-01 10:03

    Like the other posters have said, JavaScript is loose typed, so there is no differentiation in data types from float to int or vice versa.

    However, what you're looking for is

    float to int:

    Math.floor( 3.9 ); // result: 3 (truncate everything past .) or
    Math.round( 3.9 ); // result: 4 (round to nearest whole number)
    

    Depending on which you'd like. In C/C++ it would essentially be using Math.floor to convert to integer from float.

    int to float:

    var a = 10;
    a.toFixed( 3 ); // result: 10.000
    

提交回复
热议问题