簡體   English   中英

在Python中:如何使用指定數量的數字在文件中編寫浮點數?

[英]In Python: How can I write floating point numbers in a file using a specified number of figures?

我試圖寫一個文件浮點值,但我想總是用4個數字/數字表示數字。

我已經使用命令對整數執行了此操作:

f.write("%04d " % my_int_value)

在這種情況下,如果my_int_value25 ,它將在文件中打印:

0025

如果my_int_value = 2 ,它將打印在文件中:

0002

這正是我要找的!

然后 ,我嘗試使用以下命令對浮點數進行相同的操作:

f.write("%04f " % my_float_value)

但現在它不起作用。

例如,如果my_float_value = 0.03我想在文件0.030中打印

這可能嗎? 如果有人怎么做呢?

您可以通過以下幾種方式實現:

print("%.3f " % my_float_value) # Using formatting for Python2.7

要么

print("{0:.3f} ".format(my_float_value)) # Using modern string formatting

要么

print(f"{my_float_value:.3f}") # A newer form of string formatting

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM