Truncate a floating point number without rounding up

前端 未结 2 910
死守一世寂寞
死守一世寂寞 2021-02-11 20:43

I have a floating point number that I want to truncate to 3 places but I don\'t want to round up.

For example, convert 1.0155555555555555 to 1.015

2条回答
  •  礼貌的吻别
    2021-02-11 21:07

    Assuming you have a float, try this:

    (x * 1000).floor / 1000.0
    

    Result:

    1.015
    

    See it working online: ideone

提交回复
热议问题