如何限制位数?

时间:2018-02-17 15:59:50

标签: python function return digit

如果不使用任何库,我应该在代码中添加什么来返回值15.58

def solution(side):
  result = (side**2)*(3**(0.5))/4
  return result

# return = 15.5885

3 个答案:

答案 0 :(得分:0)

使用round to ceil value:

# First we take a float and convert it to a decimal
result = (side**2)*(3**(0.5))/4

# Then we round it to 2 places
output = round(result,2)
print output

您可以使用math.floor获取15.58:

import math
result = (math.floor(result * 100)) / 100.0// 15.58

答案 1 :(得分:0)

def solution(side):
   result = (side**2)*(3**(0.5))/4
   return round(result,2)

#return = 15.59

答案 2 :(得分:0)

原始结果值:15.5884572681

使用floor向下舍入以获取15.58

import math
def solution(side): 
    result = (side**2)*(3**(0.5))/4 
    return math.floor(result*100)/100
print(solution(6))  # prints 15.58

使用精确round的{​​{1}}获取2

15.59