Truncate a floating point number without rounding up

前端 未结 3 1657
长发绾君心
长发绾君心 2021-02-11 20:28

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

3条回答
  •  不知归路
    2021-02-11 21:15

    Assuming you have a float, try this:

    (x * 1000).floor / 1000.0
    

    Result:

    1.015
    

    See it working online: ideone

提交回复
热议问题