如何舍入一个值而不是单位步长

2024-04-27 11:55:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用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中的当前方式

^{pr2}$

同时返回7.0


Tags: 方法bash方式整数perlprintbeginawk
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);
}

Perl解决方案:

perl -e 'print sprintf("%1.0f",2 * shift) / 2'    6.79
7

简单的方法是:把数字除以2。在

相关问题 更多 >