简体   繁体   中英

How to convert strings to numbers in python while preserving fractional parts

Here is example

In > int('1.5')
Out > 1
In > int('10.5')
Out > 10

But I want to keep values intact. How do you do it?

Integers are only numbers that have no decimals.

-4,-3,-2,-1,0,1,2,3,4,...,65535 etc...   

Floating point numbers or Decimal numbers are allowed to represent fractions and more precise numbers

10.5, 4.9999999

If you want to take a string and get a numerical type for non-whole numbers, use float()

float('10.5')

Here is a very simple elementary school explanation of integers

Here is the python documentation of numerical types

foo = 10.5

foo2 = int(foo)

print foo, foo2

10.5, 10

Integer can one represent whole number.

If you have a known consistent number of digest after the the comma, I recommend multiplying the number by 10 to the power of X.

Or round the number to the nearest whole number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM