How to shorten a decimal 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.

When we truncate values, we remove the decimal portion of a value. But what if we want to keep a certain number of decimal places? Let’s see how to program that in Python.

IN THIS ARTICLE:

  • Truncate values in Python to a certain number of decimals
  • Examples: truncate to a number of decimal digits
    • Truncate single Python values to a decimal amount
    • Truncate a sequence to decimal places with a list comprehension
    • Truncate a list to decimal places with a for loop

# Truncate values in Python to a certain number of decimals

With Python’s math.trunc[] function we truncate floating-point values into whole numbers [Python Docs, n.d.]. That turns 4.578 into 4 and makes -2.9 into -2. But that function always truncates to an integer, without an option to keep a certain number of decimal places.

So what to do instead? Luckily, with just a bit of code we can make our own function that truncates to decimal places. Here’s how that code looks:

import math

def truncate[number, decimals=0]:
    """
    Returns a value truncated to a specific number of decimal places.
    """
    if not isinstance[decimals, int]:
        raise TypeError["decimal places must be an integer."]
    elif decimals 

Chủ Đề