如何在 f 字符串中格式化以逗号作为小数分隔符的浮点数?

问题描述 投票:0回答:6

对于 python 中的某些机器控制,我将结果写入文本文件,其他人可以将其复制到 Excel 中(这是这种情况下最方便的方法)。但是,在荷兰,Excel 有一个逗号作为小数分隔符,因此我希望文本文件中的结果“位置”为 123,456,但是当我使用这样的 f 字符串方法时:

    resultfile.write(f"Position\t{position:.5}")

这显然会导致点小数分隔符。

如何将其更改为逗号,而不迭代整个文件的末尾并用逗号替换点?

python floating-point format f-string
6个回答
14
投票

如果您想在 f 字符串中使用逗号格式化浮点数,您可以在将浮点数转换为字符串后使用替换:

position = 123.456
f"Position\t{str(position).replace('.',',')}"

第二个选择是使用Python标准库模块语言环境(但它不是线程安全的):

import locale
locale.setlocale(locale.LC_ALL, 'nl_NL')
f"Position\t{locale.format('%.3f', position)}"

第三种选择是使用库 babel(在库例程的情况下首选):

from babel.numbers import format_decimal
f"Position\t{format_decimal(position, locale='nl_NL')}"

对于给定示例,所有三个选项都会返回相同的结果:

'Position\t123,456'

3
投票

正如 @michel-de-ruiter 提到

f
格式不适用于语言环境。另一方面,您无法使用
n
格式设置精度。例如,如果您想要小数点分隔符后有 4 位数字:

import locale
locale.setlocale(locale.LC_ALL, 'nl_NL')

position = 123.45678999
print(f'{position:.4n}')  # output: 123,4 (not quite what we wanted!)

但是,您可以在格式化之前以所需的精度对数字进行舍入:

print(f'{round(position, 4):n}')  # output: 123,4567 (that's it!)

3
投票

如果您希望避免依赖关系,以下简单的函数可能会满足您的需求:

def comma_num(n,f=''):
    return ('{'+f+'}').format(n).replace('.',',')

n = 1.23

f'Whatever {comma_num(n)}'
'Whatever {}'.format(comma_num(n))
>>>'Whatever 1,23'

f'Whatever {comma_num(n,":6.4f")}'
'Whatever {}'.format(comma_num(n,':6.4f'))
>>>'Whatever 1,2300'

2
投票

如果

g
格式足够适合您,请改用
n

resultfile.write(f"Position\t{position:.7n}")

虽然

n
可以工作(使用时使用当前的语言环境设置)而不是同时使用
d
g
,但遗憾的是
f
格式没有这样的东西...


0
投票

这个怎么样:


import locale
locale.setlocale(locale.LC_ALL,'pt_PT')

def fmt(a, dec=2):
    x = int(a)
    return f".{len(str(x))+dec}n"

def main():
    # usage example
    a = 110.12345
    print(f'{a:{fmt(a)}}')
    print(f'{a:{fmt(a,3)}}')

    # here it is
    print(f"{fmt(a) = }")

if __name__ == '__main__':
    main()

给你这个:

110,12
110,123
fmt(a) = '.5n'

Process finished with exit code 0

-3
投票

更简单的解决方案可能是:

f"Position\t{position:,.5f}"
© www.soinside.com 2019 - 2024. All rights reserved.