How to Remove a Python Decimal

The Python programming language offers many options for formatting values, be they words or numbers. Numbers are often treated as “float” or “decimal” data types, which are designed for mathematical operations such as arithmetic and rounding. Formatting operations, such as removing the decimal point, sometimes involve treating numbers as “strings” instead.

Specify the number of decimal places
Open a Python shell, such as IDLE. You can find IDLE in the Python directory, which is located in “Program Files” for Windows and “Applications” for Macs. You should see the following prompt:
Recast an existing value if it is not already a float.

example:

i = “50.0001”

iNew = float(h)

type(iNew) # check if value is a float

<type ‘float’>

Use the “%f” formatting option. Customize the number of decimal places with a decimal modifier in the middle as follows: “%.2f” (Substitute the 2 for your desired precision.)

“.3 specifies three decimal places: %.3f” % 50.0001

‘.3 specifies three decimal places: 50.000’

j = 50.0001

“%.1f” % j

‘50.0’

Remove digits from the right
Open a new IDLE file.

Cast the value as a string.

k = “3.141592”

Use Python’s substring notation to remove a specified number of characters from the right regardless of the value’s precision.

k = “3.141592”

k[:len(k)-2] # the substring of k from the start to character at index: length of k minus 2

‘3.1415’

m = “100.000”

m[:len(m)-1]

‘100.00’

Remove the decimal point
Open a new IDLE file.

Cast your value as a string.

n = “0452.5”

Replace the decimal point with nothing, by using the string replace method:

n = “0452.5”

n.replace(“.”, “”)

‘04525’

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s