我正在Windows操作系统下的Python中寻找正确的德语数字格式设置方式(例如1.000,1234
)。
我尝试了locale.setlocale
,但没有成功。
相反,我编写了一个函数来提供所需的输出。
有更好的方法吗?
def ger_num(number, precision=3):
"""
returns german formatted number as string or an empty string
"""
if number is not None:
try:
my_number = "{:,f}".format(number)
except ValueError:
return ""
decimals, fraction = my_number.split(".")[0], my_number.split(".")[1]
decimals = decimals.replace(",", ".")
if precision:
return decimals + "," + fraction[:precision]
else:
return decimals
else:
return ""
答案 0 :(得分:3)
您可以使用locale.setlocale
将语言环境设置为de
,然后使用locale.format
设置电话号码的格式:
import locale
locale.setlocale(locale.LC_ALL, 'de')
print(locale.format('%.4f', 1000.1234, 1))
这将输出:
1.000,1234
答案 1 :(得分:0)
如果由于某种原因locale
对您不起作用(或不希望使用),那么最简单的其他选择可能是使用字符串替换,如this already mentioned answer中建议的那样(它给出了答案)来自PEP-378)。
您始终可以将其封装在一个函数中,也许像这样:
def format_number(number, precision=3):
# build format string
format_str = '{{:,.{}f}}'.format(precision)
# make number string
number_str = format_str.format(number)
# replace chars
return number_str.replace(',', 'X').replace('.', ',').replace('X', '.')
这对int
,float
和Decimal
很有效:
>>> format_number(1)
'1,000'
>>> format_number(1, 2)
'1,00'
>>> format_number(1, 7)
'1,0000000'
>>> format_number(1234567, 7)
'1.234.567,0000000'
>>> format_number(1234567.9988, 7)
'1.234.567,9988000'
>>> format_number(1234567.9988, 2)
'1.234.568,00'
>>> from decimal import Decimal
>>> format_number(Decimal('1234567.9988'), 2)
'1.234.568,00'
>>> format_number(Decimal('1234567.9988'), 5)
'1.234.567,99880'
>>> format_number(Decimal('1234567.9988'), 0)
'1.234.568'
>>> format_number(Decimal('123456'), 5)
'123.456,00000'
答案 2 :(得分:0)
感谢您的帮助。如果有人觉得这有用,我会在这里提供最终解决方案的代码。
ger_num.py:
events.js:174
throw er; // Unhandled 'error' event
^
TypeError: this.getJhipsterAppConfig is not a function
at module.exports.readConfig (D:\HeliosStudio_1.0.0\nodejs\node_modules\generator-jhipster-primeng\generators\app\index.js:33:47)
at Object.<anonymous> (D:\HeliosStudio_1.0.0\nodejs\node_modules\generator-jhipster-primeng\node_modules\generator-jhipster\node_modules\yeoman-generator\lib\index.js:424:27)
at D:\HeliosStudio_1.0.0\nodejs\node_modules\generator-jhipster-primeng\node_modules\run-async\index.js:25:25
at new Promise (<anonymous>)
at D:\HeliosStudio_1.0.0\nodejs\node_modules\generator-jhipster-primeng\node_modules\run-async\index.js:24:19
at self.env.runLoop.add.completed (D:\HeliosStudio_1.0.0\nodejs\node_modules\generator-jhipster-primeng\node_modules\generator-jhipster\node_modules\yeoman-generator\lib\index.js:425:13)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
Emitted 'error' event at:
at Immediate.setImmediate (D:\HeliosStudio_1.0.0\nodejs\node_modules\generator-jhipster-primeng\node_modules\generator-jhipster\node_modules\yeoman-generator\lib\index.js:433:22)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)