floor and ceil with number of decimals

前端 未结 3 1602
情话喂你
情话喂你 2021-01-05 06:51

I need to floor a float number with an specific number of decimals.

So:

2.1235 with 2 decimals --> 2.12
2.1276 with 2 decimals --> 2.12  (round         


        
3条回答
  •  太阳男子
    2021-01-05 07:35

    If regular expressions are an option, you can give this a go:

    import re
    
    def truncate(n, d):
      return float(re.search('\d+\.\d{}'.format(d), str(float(n)))[0])
    
    print(truncate(2.1235, 2))
    print(truncate(2.1276, 2))
    

    Output:

    2.12
    2.12
    

    Another solution using str.split:

    def truncate(n, d):
      s = str(float(n)).split('.')
      return float('{}.{}'.format(s[0], s[1][:d]))
    
    print(truncate(2.1235, 2))
    print(truncate(2.1276, 2))
    

    Output:

    2.12
    2.12
    

提交回复
热议问题