IT박스

파이썬으로 소수점 이하 2 자리를 반올림하는 방법은 무엇입니까?

itboxs 2020. 6. 5. 21:07
반응형

파이썬으로 소수점 이하 2 자리를 반올림하는 방법은 무엇입니까?


이 코드 (화씨에서 섭씨로 변환)의 출력에서 ​​많은 소수점을 얻습니다.

내 코드는 현재 다음과 같습니다

def main():
    printC(formeln(typeHere()))

def typeHere():
    global Fahrenheit
    try:
        Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n"))
    except ValueError:
        print "\nYour insertion was not a digit!"
        print "We've put your Fahrenheit value to 50!"
        Fahrenheit = 50
    return Fahrenheit

def formeln(c):
    Celsius = (Fahrenheit - 32.00) * 5.00/9.00
    return Celsius

def printC(answer):
    answer = str(answer)
    print "\nYour Celsius value is " + answer + " C.\n"



main()

그래서 제 질문은 소수점 둘째 자리에 대한 모든 답을 어떻게 프로그램에 적용합니까?


round 함수를 사용할 수 있습니다.이 함수는 첫 번째 인수로 숫자를 취하고 두 번째 인수는 정밀도입니다.

귀하의 경우에는 다음과 같습니다.

answer = str(round(answer, 2))

str.format()구문사용하여 소수점 이하 두 자리 표시 answer 합니다 (의 기본 값을 변경하지 않고 answer).

def printC(answer):
    print "\nYour Celsius value is {:0.2f}ºC.\n".format(answer)

어디:

  • :형식 사양을 소개합니다
  • 0 숫자 유형에 대해 기호 인식 제로 패딩을 활성화합니다.
  • .2세트 정밀도 로를2
  • f 숫자를 고정 소수점 숫자로 표시합니다

대부분의 답변은 round또는 format입니다. round때로는 반올림되며 내 경우에는 변수 을 반올림하고 표시하지 않아야했습니다.

round(2.357, 2)  # -> 2.36

여기에서 답을 찾았습니다 : 부동 소수점 숫자를 특정 소수점 이하 자릿수로 반올림하는 방법은 무엇입니까?

import math
v = 2.357
print(math.ceil(v*100)/100)  # -> 2.36
print(math.floor(v*100)/100)  # -> 2.35

또는:

from math import floor, ceil

def roundDown(n, d=8):
    d = int('1' + ('0' * d))
    return floor(n * d) / d

def roundUp(n, d=8):
    d = int('1' + ('0' * d))
    return ceil(n * d) / d

float(str(round(answer, 2)))
float(str(round(0.0556781255, 2)))

% .2f 형식을 사용하면 소수점 이하 2 자리로 내림 할 수 있습니다.

def printC(answer):
    print "\nYour Celsius value is %.2f C.\n" % answer

답을 반올림하고 싶습니다.

round(value,significantDigit)이 작업을 수행하는 일반적인 솔루션입니다, 그러나 이것은 때때로 (의 왼쪽) 즉시 열등한 숫자는 반올림있는 자리가있을 때 하나는 수학의 관점에서 기대하는 것처럼 작동하지 않습니다 5.

이 예측할 수없는 동작의 예는 다음과 같습니다.

>>> round(1.0005,3)
1.0
>>> round(2.0005,3)
2.001
>>> round(3.0005,3)
3.001
>>> round(4.0005,3)
4.0
>>> round(1.005,2)
1.0
>>> round(5.005,2)
5.0
>>> round(6.005,2)
6.0
>>> round(7.005,2)
7.0
>>> round(3.005,2)
3.0
>>> round(8.005,2)
8.01

Assuming your intent is to do the traditional rounding for statistics in the sciences, this is a handy wrapper to get the round function working as expected needing to import extra stuff like Decimal.

>>> round(0.075,2)

0.07

>>> round(0.075+10**(-2*6),2)

0.08

Aha! So based on this we can make a function...

def roundTraditional(val,digits):
   return round(val+10**(-len(str(val))-1))

Basically this adds a really small value to the string to force it to round up properly on the unpredictable instances where it doesn't ordinarily with the round function when you expect it to. A convenient value to add is 1e-X where X is the length of the number string you're trying to use round on plus 1.

The approach of using 10**(-len(val)-1) was deliberate, as it the largest small number you can add to force the shift, while also ensuring that the value you add never changes the rounding even if the decimal . is missing. I could use just 10**(-len(val)) with a condiditional if (val>1) to subtract 1 more... but it's simpler to just always subtract the 1 as that won't change much the applicable range of decimal numbers this workaround can properly handle. This approach will fail if your values reaches the limits of the type, this will fail, but for nearly the entire range of valid decimal values it should work.

So the finished code will be something like:

def main():
    printC(formeln(typeHere()))

def roundTraditional(val,digits):
    return round(val+10**(-len(str(val))-1))

def typeHere():
    global Fahrenheit
    try:
        Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n"))
    except ValueError:
        print "\nYour insertion was not a digit!"
        print "We've put your Fahrenheit value to 50!"
        Fahrenheit = 50
    return Fahrenheit

def formeln(c):
    Celsius = (Fahrenheit - 32.00) * 5.00/9.00
    return Celsius

def printC(answer):
    answer = str(roundTraditional(answer,2))
    print "\nYour Celsius value is " + answer + " C.\n"

main()

...should give you the results you expect.

You can also use the decimal library to accomplish this, but the wrapper I propose is simpler and may be preferred in some cases.


Edit: Thanks Blckknght for pointing out that the 5 fringe case occurs only for certain values here.


You can use the string formatting operator of python "%". "%.2f" means 2 digits after the decimal point.

def typeHere():
    try:
        Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n"))
    except ValueError:
        print "\nYour insertion was not a digit!"
        print "We've put your Fahrenheit value to 50!"
        Fahrenheit = 50
    return Fahrenheit

def formeln(Fahrenheit):
    Celsius = (Fahrenheit - 32.0) * 5.0/9.0
    return Celsius

def printC(answer):
    print "\nYour Celsius value is %.2f C.\n" % answer

def main():
    printC(formeln(typeHere()))

main()

http://docs.python.org/2/library/stdtypes.html#string-formatting


You can use the round function.

round(80.23456, 3)

will give you an answer of 80.234

In your case, use

answer = str(round(answer, 2))

Hope this helps :)


Here is an example that I used:

def volume(self):
    return round(pi * self.radius ** 2 * self.height, 2)

def surface_area(self):
    return round((2 * pi * self.radius * self.height) + (2 * pi * self.radius ** 2), 2)

Not sure why, but '{:0.2f}'.format(0.5357706) gives me '0.54'. The only solution that works for me (python 3.6) is the following:

def ceil_floor(x):
    import math
    return math.ceil(x) if x < 0 else math.floor(x)

def round_n_digits(x, n):
    import math
    return ceil_floor(x * math.pow(10, n)) / math.pow(10, n)

round_n_digits(-0.5357706, 2) -> -0.53 
round_n_digits(0.5357706, 2) -> 0.53

You can use round operator for up to 2 decimal

num = round(343.5544, 2)
print(num) // output is 343.55

As you want your answer in decimal number so you dont need to typecast your answer variable to str in printC() function.

and then use printf-style String Formatting


round(12.3956 - 0.005, 2)  # minus 0.005, then round.

The answer is from: https://stackoverflow.com/a/29651462/8025086

참고URL : https://stackoverflow.com/questions/20457038/how-to-round-to-2-decimals-with-python

반응형