博客
关于我
python 保留精度及增加去除数字的千位分隔符(金额化数字)
阅读量:797 次
发布时间:2023-03-06

本文共 1217 字,大约阅读时间需要 4 分钟。

Python数字格式化处理技巧

在Python编程中,处理数字格式化问题是一个常见的需求。以下是一些实用的技巧,帮助你轻松完成各种数字格式化任务。

1. 保留指定位数的小数

当需要对浮点数进行四舍五入时,可以使用格式化字符串来实现。常见的有两种方法:

  • 使用`print('%.3f' % 3141456.1415926)`,这将保留三位小数并进行四舍五入。如上述代码执行后,结果会是`3141456.142`。
  • 使用`print('{:.2f}'.format(1456.14159))`,同样也是四舍五入的方式,结果会是`1456.142`。

如果不需要四舍五入而是直接截断,可以采用以下方法:

```pythona = 1234.56789print(int(a * 1000) / 1000) # 输出:1234.567```

或者使用字符串截取的方法:

```pythona = 2.345678a_str = str(a).split('.')a_int_part = a_str[0]a_decimal_part = a_str[1]截取指定位数:a_decimal_part = a_decimal_part[0:3]最终结果:a_int_part + '.' + a_decimal_partnew_a = float(a_int_part + '.' + a_decimal_part)print(new_a) # 2.345```

2. 去掉数字中的千分位

当需要去掉数字中的千分位时,可以采用不同的方法,具体取决于数据的来源形式:

1. 如果数据是纯数字的字符串:

```pythona = '12,235,454.123654'b = a.replace(',', '') # 去掉所有逗号print(b) # 输出:12235454.123654```

2. 如果数据包含其他字符:

```pythons = "Today is Sunday, I'm shy,I bought $ 100,000.$ 12,345.34"import red = re.sub(r'\d+,\d+', '', s) # 使用正则表达式替换千分位print(d) # 输出:Today is Sunday, I'm shy,I bought $ 100000.$ 12345.34```

3. 添加数字中的千分位

当需要在数字中添加千分位时,可以使用Python的格式化功能:

```pythonp = '{:,.3f}'.format(float('23543676.3476879324'))print(p) # 输出:23,543,676.348```

此方法会自动将数字格式化为千分位,适用于需要统一格式的场景。

这些技巧可以帮助你在不同场景下高效处理数字格式化问题,节省开发时间,同时确保输出结果的准确性和一致性。

转载地址:http://mdofk.baihongyu.com/

你可能感兴趣的文章
python socket模块_Python socket模块实现TCP服务端客户端
查看>>
Python SOCKS5代理客户端HTTPS
查看>>
Python Soc网络分析:通过使用函数迭代列表来计算机会网络
查看>>
Python SQL和NoSQL数据库操作实战
查看>>
python stdout flush_sys.stdout.flush()方法的用法
查看>>
python string 运算
查看>>
Python str与bytes之间的转换
查看>>
Python subprocess ffmpeg
查看>>
python subprocess Permission denied Errno 13
查看>>
Python subprocess.call - 将变量添加到 subprocess.call
查看>>
Python Subprocess.Popen 从一个线程
查看>>
Python subprocess.Popen 作为 Windows 上的不同用户
查看>>
Python subprocess.Popen() 等待完成
查看>>
Python Sympy模块NoConversion:收敛到根失败;请尝试n<;15或MaxSteps>;50
查看>>
python time模块
查看>>
Python Tkinter Multiple Windows 教程
查看>>
Python tkinter 中的多处理
查看>>
Python tweepy写入到sqlite3 db
查看>>
Python TypeError:格式字符串的参数不足
查看>>
Python UI自动化测试Page Objects企业级实战
查看>>