如何根据语言环境变量格式化浮点数以供显示?

How to format a floating point for display based on locale environment variables?

假设我有几个浮点数要在 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}"

实际输出:

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.

格式化参数

那么如何显示存储在POSIX或bc格式但显示反映LC_NUMERIC设置的任意浮点数?

如果我想要代码的法语部分,输出如下怎么办?

法语的预期输出:

La vitesse de la lumière dans le vide est :
C=299792458 m/s

π≈3,1415926536

这是 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

输出

script.sh: line 4: printf: 3.14: invalid number
Bad  : 0,000000
Good : 3,140000