awk中符点型小数去掉小数点转换成整数的方法

栏目: 服务器 · 发布时间: 7年前

内容简介:在写shell脚本时,会遇到要把一个符点数转换成整数的情况。之前线上一个shell脚本在用awk从文本中读取出一个带两位小数的符点数后,是直接把它乘以100转换成整数的。脚本一直运行正常,直到后面遇到了一个符点数有两种方法可以解决这个问题:1通过

在写 shell 脚本时,会遇到要把一个符点数转换成整数的情况。之前线上一个shell脚本在用awk从文本中读取出一个带两位小数的符点数后,是直接把它乘以100转换成整数的。脚本一直运行正常,直到后面遇到了一个符点数 19004.44 ,它在乘以100后得到的不是 1900444 而是科学记数 1.90044e+06 ,导致导入数据库失败。后面测试发现符点数 19004.42 也存在同样的问题,如果下图所示:

awk中符点型小数去掉小数点转换成整数的方法

1 解决方法

有两种方法可以解决这个问题:1通过 sub 或者 gsub 函数把符点数的小数点去掉;2和C/C++那样通过 printf 占位符格式化。

测试结果如下所示:

# Description:   awk中符点型小数去掉小数点转换成整数的方法
# (c) 2018.03.28 vfhky https://typecodes.com/linux/awkdecimaltoint1.html


#### 方法一:使用sub函数进行替换(把小数点去掉)
[vfhky@typecodes shell]$ echo 19004.44 | awk '{sub(/\./,"",$1); print $1}'
1900444
[vfhky@typecodes shell]$ echo 0.44 | awk '{sub(/\./,"",$1); print $1}'
044
#### 小数点前面的0可以通过int函数强制转换去掉
[vfhky@typecodes shell]$ echo 0.44 | awk '{sub(/\./,"",$1); print int($1)}'
44
[vfhky@typecodes shell]$

#### 方法二:使用printf函数格式化
[vfhky@typecodes shell]$ echo 19004.44 | awk '{printf("%.0f\n", 100*$1)}'
1900444
[vfhky@typecodes shell]$ echo 0.44 | awk '{printf("%.0f\n", 100*$1)}'
44
[vfhky@typecodes shell]$

exit 0

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Software Engineering for Internet Applications

Software Engineering for Internet Applications

Eve Andersson、Philip Greenspun、Andrew Grumet / The MIT Press / 2006-03-06 / USD 35.00

After completing this self-contained course on server-based Internet applications software, students who start with only the knowledge of how to write and debug a computer program will have learned ho......一起来看看 《Software Engineering for Internet Applications》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具