如何在 bash 中的 printf 命令中更改小数点分隔符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12845638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i change the decimal separator in the printf command in bash?
提问by Ferdinando Randisi
I use the Italian localization of Cygwin, and therefore my printf command uses commas to separate floats, and won't understand dot-separated floats
我使用 Cygwin 的意大利语本地化,因此我的 printf 命令使用逗号来分隔浮点数,并且无法理解点分隔的浮点数
$ printf "%f" 3.1415
-bash: printf: 3.1415: invalid number
0,000000
$ printf "%f" 3,1415
3,141500
This gives rise to several problems because basically everything else uses a dot to separate decimal digits.
这引起了几个问题,因为基本上其他所有内容都使用点来分隔十进制数字。
How can I change the decimal separator from comma to dot?
如何将小数点分隔符从逗号更改为点?
采纳答案by Ferdinando Randisi
There are several local variables tha control the localization of cygwin (or of any bash shell, for the matter). You can see them along with their value using the localecommand. You should see something like this:
有几个局部变量控制 cygwin(或任何 bash shell,就此而言)的本地化。您可以使用locale命令查看它们及其值。您应该会看到如下内容:
$ locale
LANG=it_IT.UTF-8
LC_CTYPE="it_IT.UTF-8"
LC_NUMERIC="it_IT.UTF-8"
LC_TIME="it_IT.UTF-8"
LC_COLLATE="it_IT.UTF-8"
LC_MONETARY="it_IT.UTF-8"
LC_MESSAGES="it_IT.UTF-8"
LC_ALL=
You can see the possible values of the variables by using locale -va. Their are all formatted like _.UTF-8. UTF-8 is optional.
In order to switch to North American float separation style simply set LC_NUMERIC to its American value.
您可以使用 来查看变量的可能值locale -va。它们的格式都像 _.UTF-8。UTF-8 是可选的。为了切换到北美浮动分隔样式,只需将 LC_NUMERIC 设置为其美国值。
$ export LC_NUMERIC="en_US.UTF-8"
Simply setting the variable LC_NUMERIC as if it were a regular variable won't work, you need to use the export command.
简单地将变量 LC_NUMERIC 设置为常规变量是行不通的,您需要使用导出命令。
You can put this in the header of your scripts, or you can make it permanent by adding it to your ~/.bashrcor your ~/.bash_profile
您可以将其放在脚本的标题中,也可以通过将其添加到您的~/.bashrc或您的~/.bash_profile
Hope this was helpful!
希望这是有帮助的!
回答by jesjimher
If you don't want to mess with system configuration, you can respect your locale but make sure your script uses dots for decimals with:
如果您不想弄乱系统配置,您可以尊重您的语言环境,但请确保您的脚本使用点作为小数点:
$ printf "%f" 3.5
-bash: printf: 3,5: invalid number
0.000000
$ LANG=C printf "%f" 3.5
3.500000

