How do you convert a decimal to 2 decimal places in python?

You want to round your answer.

round(value,significantDigit) is the ordinary solution to do this, however this sometimes does not operate as one would expect from a math perspective when the digit immediately inferior (to the left of) the digit you're rounding to has a 5.

Here's some examples of this unpredictable behavior:

>>> 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), digits)

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.

In this article, we will learn to round of floating value to two decimal places in Python. We will use some built-in functions and some custom codes as well. Let's first have a quick look over what are Python variables and then how to round off is performed in Python.

Python Float Type

These are floating point real values and are also called floats. Floating-point numbers are written with a decimal point separating the integer part and the fractional part.

Here are some examples of float values- 1.23. 1.08, 45.60, 45.6123004, 1.23e5 (This represents scientific notation of float value where the decimal part is Mantissa and the exponential part(e) is Exponent).

Python Float Type Example

Now, let us print a float number and observe the following output.

Take a variable x, store any float value and print the variable x using the print statement.

x = 1.234
print(x)


1.234

Now, if you observe the above output of the print statement, you will see that there are three decimal places after the decimal point. A question arises here that, what if the programmer needs to print only the float value to a given number of decimal places.

Like for example, in the above code, x = 1.234. The programmer needs to print only two decimal places after the decimal point i.e. x value should be 1.23. So for this purpose, we can use the round() function.

Round to Two Decimals using round() Function

The round() function is a built-in function that is used to get a floating-point number rounded to the specified number of decimals.

Syntax

round(number, digit)

If digit (second parameter) is not given, it returns the nearest integer to the given number, else it returns the number rounded off to the given digit value.

# for integers
print(round(10))

# for floating point
print(round(10.7,2))
print(round(5.5678,2))
print(round(-12.481,2))


10
10.7
5.57
-12.48

In integer, there is no decimal point so the answer remains the same. In floating points, 10.7 gives 10.7 as the precision value is set to 2 decimal places while in 5.5678, the value changes to 5.57. This value rounded off to two decimal places.

Round to Two Decimals using format() Function

We can use str.format() function to display float value with two decimal places. It keeps the actual value intact and is simple to implement.

Syntax

{:0.2f}, .format(number)

Example 1

print("Sir, your shopping bill amount is Rs. {:0.2f}.".format(206.551))


Sir, your shopping bill amount is Rs. 206.55.

Example 2

We can also use % instead of format() function to get formatted output. It is similar to the format specifier in the print function of the C language. Just use the formatting with %.2f which gives you round down to 2 decimal points.

number= 7.361

print("\"Sir, your shopping bill amount is Rs. %.2f ." % number)


Sir, your shopping bill amount is Rs. 7.36.

Round to Two Decimals using the ceil() Function

Python math module provides ceil() and floor() functions to rounded up and rounded down the any value. The floor and ceiling functions generally map a real number to the largest previous or smallest following integer which has zero decimal places. So to use them for 2 decimal places the number is first multiplied by 100 to shift the decimal point and is then divided by 100 afterward to compensate.

Example

#using round fucntion
round(2.357, 2)  


#using math.ceil() and math.floor()
import math
num = 2.357
print(math.ceil(num*100)/100) 
print(math.floor(num*100)/100) 


2.36
2.36
2.35

Round to Two Decimals using the decimal Module

Python provides a decimal module that contains several functions to deal with decimal values. We can use it to round off float value to the two decimal points. This method of using decimals will round decimals with super rounding powers.

#import decimal
from decimal import Decimal,

value = Decimal(16.0/7)
result = Decimal(value.quantize(Decimal('.01'), rounding = ROUND_HALF_UP))
print(result)


2.29

Example

This is an example of rounding imports Decimal and round decimal by setting precision values explicitly.

#import decimal 
from decimal import getcontext, Decimal

# Set the precision
getcontext().prec = 3

# Execute 1/7, however cast both numbers as decimals
result = Decimal(16.0)/Decimal(7)

# Your output will return w/ 6 decimal places
print(result)


2.29

This precision takes the total number of digits to be printed. If prec = 2, then the output would be 2.3.

Note:

The behavior of round() for floats can be surprising. For example, round(2.675, 2) gives 2.67 instead of the expected 2.68.

It's a result of the fact that most decimal fractions can't be represented exactly as a float. When the decimal 2.675 is converted to a binary floating-point number, it's again replaced with a binary approximation, whose exact value is: 2.67499999999999982236431605997495353221893310546875. Due to this, it is rounded down to 2.67.

If you're in a situation where this precision is needed, consider using the decimal module, as given above.

Conclusion

In this article, we learned to round values to two decimal places by using several built-in functions such as math.ceil(), math.floor(), decimal module, round() etc. We used some custom codes as well.

How do you convert to 2 decimal places in Python?

Python's round() function requires two arguments. First is the number to be rounded. Second argument decides the number of decimal places to which it is rounded. To round the number to 2 decimals, give second argument as 2.

How do you change decimal places in Python?

Use str..
value = 3.3333333333..
formatted_string = "{:.2f}". format(value) format to two decimal places..
float_value = float(formatted_string).
print(float_value).

How do you round to 2 numbers in Python?

Python has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits .

How do you convert to 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.