# Python将字符串转换为浮点数

We can convert a string to float in Python using float() function. It’s a built-in function to convert an object to floating point number. Internally float() function calls specified object __float__() function.

## Python将字符串转换为浮点数 (Python Convert String to float)

Let’s look at a simple example to convert a string to float in Python.

s = '10.5674'

f = float(s)

print(type(f))
print('Float Value =', f)

Output:

<class 'float'>
Float Value = 10.5674

### 为什么我们需要将字符串转换为float？ (Why do we need to convert a string to float?)

If we are getting float value from user input through the terminal or reading it from a file, then they are string objects. So we have to explicitly convert them to float so that we can perform necessary operations on it, such as addition, multiplication etc.

input_1 = input('Please enter first floating point value:\n')
input_1 = float(input_1)

input_2 = input('Please enter second floating point value:\n')
input_2 = float(input_2)

print(f'Sum of {input_1} and {input_2} is {input_1+input_2}')
try-except block to catch exceptions in case of invalid input from user. try-except块来捕获异常。

If you are not familiar with string formatting using f prefix, please read f-strings in Python.

## Python将float转换为String (Python Convert float to String)

We can convert float to a string easily using str() function. This might be required sometimes where we want to concatenate float values. Let’s look at a simple example.

f1 = 10.23
f2 = 20.34
f3 = 30.45

# using f-string from Python 3.6+, change to format() for older versions
print(f'Concatenation of {f1} and {f2} is {str(f1) + str(f2)}')
print(f'CSV from {f1}, {f2} and {f3}:\n{str(f1)},{str(f2)},{str(f3)}')
print(f'CSV from {f1}, {f2} and {f3}:\n{", ".join([str(f1),str(f2),str(f3)])}')

Output:

Concatenation of 10.23 and 20.34 is 10.2320.34
CSV from 10.23, 20.34 and 30.45:
10.23,20.34,30.45
CSV from 10.23, 20.34 and 30.45:
10.23, 20.34, 30.45

If we don’t convert float to string in the above program, join() function will throw exception. Also, we won’t be able to use + operator to concatenate as it will add the floating point numbers.

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: float() official documentation

• 2
点赞
• 0
评论
• 6
收藏
• 一键三连
• 扫一扫，分享海报

03-07
07-17 4万+

03-25 7352
12-05 2069
02-24 1万+
07-18 6948
12-20 2267
08-28 1万+
11-28 4万+
07-29 4万+
©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。