Léa*_*ris 8 floating-point bash locale
可以说我有几个浮点数要在Bash脚本中打印。但是我希望浮点数相应地显示在LC_NUMERIC
语言环境环境变量中。
#!/usr/bin/env bash
# For consistent/reproducible error messages in this sample code
LANGUAGE=C
# The speed of light in vacum in m.s
declare -r const_C=299792458
# Declare separately when assigning command output
declare -- const_pi
# ? is 4 × arc-tangent of 1, using bc calculator with math library
typeset -r const_pi="$(bc --mathlib <<<'scale=20; 4*a(1)')"
# Do it in US's English
LC_NUMERIC=en_US.utf8
printf 'LC_NUMERIC=%s\n' "${LC_NUMERIC}"
printf 'Speed of light in vacuum is:\nC=%.f m/s\n\n?=%.10f\n' \
"${const_C}" \
"${const_pi}"
echo $'\n'
# Do it in France's French
# it fails because floating point format
# changes for printf parameters
LC_NUMERIC=fr_FR.utf8
printf 'LC_NUMERIC=%s\n' "${LC_NUMERIC}"
printf 'La vitesse de la lumière dans le vide est?:\nC=%.f m/s\n\n??%.10f\n' \
"${const_C}" \
"${const_pi}"
Run Code Online (Sandbox Code Playgroud)
实际输出:
#!/usr/bin/env bash
# For consistent/reproducible error messages in this sample code
LANGUAGE=C
# The speed of light in vacum in m.s
declare -r const_C=299792458
# Declare separately when assigning command output
declare -- const_pi
# ? is 4 × arc-tangent of 1, using bc calculator with math library
typeset -r const_pi="$(bc --mathlib <<<'scale=20; 4*a(1)')"
# Do it in US's English
LC_NUMERIC=en_US.utf8
printf 'LC_NUMERIC=%s\n' "${LC_NUMERIC}"
printf 'Speed of light in vacuum is:\nC=%.f m/s\n\n?=%.10f\n' \
"${const_C}" \
"${const_pi}"
echo $'\n'
# Do it in France's French
# it fails because floating point format
# changes for printf parameters
LC_NUMERIC=fr_FR.utf8
printf 'LC_NUMERIC=%s\n' "${LC_NUMERIC}"
printf 'La vitesse de la lumière dans le vide est?:\nC=%.f m/s\n\n??%.10f\n' \
"${const_C}" \
"${const_pi}"
Run Code Online (Sandbox Code Playgroud)
这是一个完美的预期结果,因为printf
%f
format希望参数根据进行格式化LC_NUMERIC
。
然后,如何显示以POSIX或bc
格式存储但显示的任意浮点数反映了设置LC_NUMERIC
?
如果我想要代码的法语部分,并输出以下内容,该怎么办?
法语预期产量:
LC_NUMERIC=en_US.utf8
Speed of light in vacuum is:
C=299792458 m/s
?=3.1415926536
LC_NUMERIC=fr_FR.utf8
La vitesse de la lumière dans le vide est?:
C=299792458 m/s
a.sh: line 29: printf: 3.14159265358979323844: invalid number
??3,0000000000
Run Code Online (Sandbox Code Playgroud)
这是Bash自己内置的printf命令的问题。独立的printf可以正常工作。
LC_NUMERIC=fr_FR.UTF8 printf 'Bad : %f\n' 3.14
env LC_NUMERIC=fr_FR.UTF8 printf 'Good : %f\n' 3.14
Run Code Online (Sandbox Code Playgroud)
输出量
script.sh: line 4: printf: 3.14: invalid number
Bad : 0,000000
Good : 3,140000
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
101 次 |
最近记录: |