bash - 如何根据语言环境变量格式化 float 以供显示?

标签 bash floating-point locale

假设我有几个 float 要在 Bash 脚本中打印。 但我希望根据 LC_NUMERIC 语言环境变量显示 float 。

#!/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 格式存储但显示反射(reflect) LC_NUMERIC 设置的任意 float ?

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

法语的预期输出:

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

关于bash - 如何根据语言环境变量格式化 float 以供显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56909523/

相关文章:

c++ - 无法从 map 获取字符分类信息

mysql - C 应用程序特殊字符 Äöü 未在 MySQL 和终端中正确显示

linux - 编写运行其他用户拥有的另一个 shell 脚本的 shell 脚本

bash - 仅使用 bash 获取 Ubuntu 版本号

C++:清除单精度 float 的位

php - Symfony 3 将所有路由重定向到当前语言环境版本

linux - 如何在bash中输出目录的不可读内容

bash - 实时修改shell stdout

floating-point - 为什么高精度浮点格式具有这么多指数位?

在jasper报告中以指定格式显示浮点值的java代码