Truncate a floating point number without rounding up

前端 未结 3 1659
长发绾君心
长发绾君心 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:06

    You can also convert to a BigDecimal, and call truncate on it.

    1.237.to_d.truncate(2).to_f # will return 1.23
    
    0 讨论(0)
  • 2021-02-11 21:15

    Since ruby 2.4 Float#truncate method takes as an optional argument a number of decimal digits:

    1.0155555555555555.truncate(3)
    # => 1.015
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题