BASH 将浮点数四舍五入到最接近的十分之一

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13572355/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:52:00  来源:igfitidea点击:

BASH rounding float to the nearest tenth

bashdecimalrounding

提问by Francis Batalla

How do you round floats to the nearest tenths using bc. I have a variable called loadMin

你如何使用 bc 将浮点数舍入到最近的十分之一。我有一个名为 loadMin 的变量

loadMin=$(uptime | cut -d" " -f14 | cut -c 1-4) 

which returns the load averages per minute with two decimal places. I.e 0.01 0.02 0.09. I need the number to be rounded to the nearest tenth. For example 0.01 rounded to 0.0 or 1.09 rounded to 1.1

它返回带有两位小数的每分钟平均负载。即 0.01 0.02 0.09。我需要将数字四舍五入到最接近的十分之一。例如 0.01 舍入为 0.0 或 1.09 舍入为 1.1

Any help is appreciated.

任何帮助表示赞赏。

回答by gniourf_gniourf

Why use bc? printfwill happily do that:

为什么使用bcprintf会很乐意这样做:

printf "%.1f" "$loadMin"

If you need to put the result in a variable:

如果需要将结果放入变量中:

printf -v variable "%.1f" "$loadMin"

回答by sampson-chen

You can do this in one go with awk:

您可以一次性完成awk

loadMin=$(uptime | awk '{printf "%0.1f", }')

Explanation:

解释:

  • Instead of using cut, use awkinstead to make these easier
  • awkdelimit on spaces and tabs by default and separates each line into fields.
  • '{printf "%0.1f", $14}': print the 14th field as a floating number, rounded to the nearest 1 decimal place.
  • 而不是使用cutawk而是使用来使这些更容易
  • awk默认情况下分隔空格和制表符,并将每行分隔为字段。
  • '{printf "%0.1f", $14}': 将第 14 个字段打印为浮点数,四舍五入到最接近的 1 位小数。