问题描述
让我们说我要在Bash脚本中打印几个浮点数.但是我希望将浮点数显示在LC_NUMERIC
区域设置环境变量中.
Lets say I have several floating point numbers to print in a Bash script.But I want the floating points numbers displayed accordingly to the LC_NUMERIC
locale environment variable.
#!/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}"
实际输出:
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
这是一个完美的预期结果,因为printf
%f
格式要求参数根据LC_NUMERIC
进行格式化.
This is a perfectly expected result because printf
%f
format expects the argument be formatted according to LC_NUMERIC
.
然后如何显示以POSIX或bc
格式存储的任意浮点数,但显示时会反映LC_NUMERIC
的设置?
Then how do you display arbitrary floating-point numbers that are stored in POSIX or bc
's format but having display reflect the settings of LC_NUMERIC
?
如果我想要代码的法文部分并显示以下输出怎么办?
What if I want the French part of the code, with the following output?
法语的预期输出:
La vitesse de la lumière dans le vide est :
C=299792458 m/s
π≈3,1415926536
推荐答案
这是Bash自己内置的printf命令的问题.独立的printf可以正常工作.
This is a problem with Bash's own built in printf command. The standalone printf works OK.
LC_NUMERIC=fr_FR.UTF8 printf 'Bad : %f\n' 3.14
env LC_NUMERIC=fr_FR.UTF8 printf 'Good : %f\n' 3.14
输出
script.sh: line 4: printf: 3.14: invalid number
Bad : 0,000000
Good : 3,140000
这篇关于如何根据区域设置环境变量设置浮点格式以进行显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!