Python 如何舍入一个值而不是单位步长
我正在尝试使用awk在bash中舍入两个十进制值。例如:如果值为6.79Python 如何舍入一个值而不是单位步长,python,perl,bash,rounding,Python,Perl,Bash,Rounding,我正在尝试使用awk在bash中舍入两个十进制值。例如:如果值为6.79 awk 'BEGIN {rounded = sprintf("%.0f", 6.79); print rounded }' 这给了我7分 有没有一种方法可以不舍入到最接近的整数(1,2,3,…),而是以0.5(0,0.5,1,1.5,2,2.5…)的步长舍入 使用python或perl的任何替代方法也可以。python中的当前方式 python -c "from math import ceil; print round
awk 'BEGIN {rounded = sprintf("%.0f", 6.79); print rounded }'
这给了我7分
有没有一种方法可以不舍入到最接近的整数(1,2,3,…),而是以0.5(0,0.5,1,1.5,2,2.5…)的步长舍入
使用python或perl的任何替代方法也可以。python中的当前方式
python -c "from math import ceil; print round(6.79)"
还返回7.0Perl解决方案:
perl -e 'print sprintf("%1.0f",2 * shift) / 2' -- 6.79
7
诀窍很简单:将数字乘以2,四舍五入,再进行除法。这里有一个通用子程序,用于将给定精度的数字四舍五入到最接近的值: 我举了一个你想要的四舍五入的例子,即0.5,我已经测试过了,即使是负浮点数,它也能完美地工作
#!/usr/bin/env perl
use strict;
use warnings;
for(my $i=0; $i<100; $i++){
my $x = rand 100;
$x -= 50;
my $y =&roundToNearest($x,0.5);
print "$x --> $y\n";
}
exit;
############################################################################
# Enables to round any real number to the nearest with a given precision even for negative numbers
# argument 1 : the float to round
# [argument 2 : the precision wanted]
#
# ie: precision=10 => 273 returns 270
# ie: no argument for precision means precision=1 (return signed integer) => -3.67 returns -4
# ie: precision=0.01 => 3.147278 returns 3.15
sub roundToNearest{
my $subname = (caller(0))[3];
my $float = $_[0];
my $precision=1;
($_[1]) && ($precision=$_[1]);
($float) || return($float); # no rounding needed for 0
# ------------------------------------------------------------------------
my $rounded = int($float/$precision + 0.5*$float/abs($float))*$precision;
# ------------------------------------------------------------------------
#print "$subname>precision:$precision float:$float --> $rounded\n";
return($rounded);
}
#/usr/bin/env perl
严格使用;
使用警告;
for(my$i=0;$i 273返回270
#ie:precision没有参数意味着precision=1(返回有符号整数)=>-3.67返回-4
#ie:precision=0.01=>3.147278返回3.15
近圆度{
我的$subname=(调用方(0))[3];
我的$float=$\u0];
我的$precision=1;
($u[1])&($精度=$[1]);
($float)|返回($float)#0不需要四舍五入
# ------------------------------------------------------------------------
my$rounded=int($float/$precision+0.5*$float/abs($float))*$precision;
# ------------------------------------------------------------------------
#打印“$subname>precision:$precision float:$float-->$rounded\n”;
回报(四舍五入);
}