gpt4 book ai didi

python - 以印度/美国表示法转换数字以值的变化结束

转载 作者:行者123 更新时间:2023-12-04 07:40:13 25 4
gpt4 key购买 nike

我试图用印度/美国符号表示数字,但我给出的值和输出不一样。请检查代码。

import locale
result = 1
for i in range(1,65):
result = result*i
print (result)

output: 126886932185884164103433389335161480802865516174545192198801894375214704230400000000000000

print(f'{result:,}')

output: 126,886,932,185,884,164,103,433,389,335,161,480,802,865,516,174,545,192,198,801,894,375,214,704,230,400,000,000,000,000

locale.setlocale(locale.LC_MONETARY, 'en_IN')
print(locale.currency(result, grouping=True))

output:₹1,26,88,69,32,18,58,84,16,54,37,80,68,97,58,51,22,92,52,90,11,90,29,06,47,05,20,97,78,50,85,45,10,34,77,59,05,11,63,70,67,40,17,89,440.00

locale.setlocale(locale.LC_MONETARY, 'en_US')
print(locale.currency(result, grouping=True))

output:$126,886,932,185,884,165,437,806,897,585,122,925,290,119,029,064,705,209,778,508,545,103,477,590,511,637,067,401,789,440.00
如果您注意到 print(f'{result:,}')结果的值没有改变,但问题出在语言环境包中,结果和输出从 12688693218588416 改变了。 .
问题:
1.为什么值会变化?
2.如何纠正?

最佳答案

它看起来像 locale.currency()正在将您的输入转换为 float 。我不知道如何解决这个问题,但您可以使用以下替代方法:

import locale

def big_money(val, loc):
locale.setlocale(locale.LC_MONETARY, loc)
retval = locale.localeconv()["currency_symbol"] + locale.format_string("%i", val, grouping=True, monetary=True)
locale.setlocale(locale.LC_MONETARY, "")
return retval

result = 126886932185884164103433389335161480802865516174545192198801894375214704230400000000000000

print(big_money(result, "en_IN"))
print(big_money(result, "en_US"))
这给了我:
?1,26,88,69,32,18,58,84,16,41,03,43,33,89,33,51,61,48,08,02,86,55,16,17,45,45,19,21,98,80,18,94,37,52,14,70,42,30,40,00,00,00,00,00,000
$126,886,932,185,884,164,103,433,389,335,161,480,802,865,516,174,545,192,198,801,894,375,214,704,230,400,000,000,000,000
实际上反射(reflection)这一点,我认为这种方法根本不应该与本地混为一谈,因此请使用:
import locale

def big_money(val):
return locale.localeconv()["currency_symbol"] + locale.format_string("%i", val, grouping=True, monetary=True)

result = 126886932185884164103433389335161480802865516174545192198801894375214704230400000000000000

locale.setlocale(locale.LC_MONETARY, "en_IN")
print(big_money(result))

locale.setlocale(locale.LC_MONETARY, "en_US")
print(big_money(result))
最后你仍然得到:
?1,26,88,69,32,18,58,84,16,41,03,43,33,89,33,51,61,48,08,02,86,55,16,17,45,45,19,21,98,80,18,94,37,52,14,70,42,30,40,00,00,00,00,00,000
$126,886,932,185,884,164,103,433,389,335,161,480,802,865,516,174,545,192,198,801,894,375,214,704,230,400,000,000,000,000

关于python - 以印度/美国表示法转换数字以值的变化结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67520737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com