舍入机制最接近0.05

问题描述 投票:9回答:10

我想通过使用php4,5.2及以下(而不是5.3)来解决舍入机制。目前我正在进行0.05舍入,类似这样的页面:

http://www.bnm.gov.my/index.php?ch=209&pg=657&ac=568

before rounding | after rounding

          89.90 | 89.90

          89.91 | 89.90

          89.92 | 89.90

          89.93 | 89.95

          89.94 | 89.95

          89.95 | 89.95

          89.96 | 89.95

          89.97 | 89.95

          89.98 | 90.00

          89.99 | 90.00

我尝试使用字符串将其拆分并手动添加,但不是一个很好的解决方案,希望在这里可以找到解决它的人。

php rounding
10个回答
14
投票

使用此功能

function rndfunc($x){
  return round($x * 2, 1) / 2;
}

0
投票

谢谢@mauris解决我在马来西亚GST舍入机制问题上的解决方案。它也适用于SQL。

DECLARE @tempTable AS TABLE(Number Decimal(20,4));

插入@tempTable VALUES(89.90),(89.91),(89.92),(89.93),(89.94),(89.95),(89.96),(89.97),(89.98),(89.99)

SELECT Number,round(Number * 2,1)/ 2 AS'Rounded'FROM @tempTable


5
投票

从概念上讲,程序可以如下:

  1. 除以0.05 或乘以(1 / 0.05)
  2. 舍入到最接近的整数
  3. 乘以0.05

1
投票

您基本上想要将值映射到网格。网格定义为a multiple of .05。通常,您需要找到您的值之间的被乘数。

表中没有的是负数。您需要决定是否从零(对称)或始终在同一方向(即正)舍入。

码:

$step = .05;
$multiplicand = floor( $value / $step );
$rest = $value % $step ;
if( $rest > $step/2 ) $multiplicand++; // round up if needed
$roundedvalue = $step*$multiplicand;

0
投票

乘以2,然后再舍入,然后除以2。


0
投票

暗示:-

$ input1 = 24.05;

$ things = abs($ input * 20); // 481“.05”s

$ tenpcnt = abs($ things / 10); // 48“.05”s

$ output = $ tencent / 20;

echo $ output; // 2.40


0
投票
function round5Sen ($value) { 

    return number_format(round($value*20,0)/20,2,'.','');
} 

echo round5Sen(155.13);
echo "\n";
echo round5Sen(155.12);
echo "\n";
echo round5Sen(155.0);
echo "\n";
echo round5Sen(155.18);
echo "\n";

0
投票

我确信有更优雅的解决方案,但这似乎适合任务:

<?php

// setup test
$start_num = 89.90;
$iterations = 10;

// loop through test numbers
for ($i = 0; $i < $iterations; $i++) {
  nickleRound($start_num + (0.01 * $i));
  echo "\n\n";
}

//
function nickleRound($num) {
  $p = 0.05;
  echo "\n" . 'p= ' . $p;

  $num = round($num, 2);
  echo "\n" . 'num= ' . $num;

  $r = ($num / $p);
  echo "\n" . 'r= ' . $r;

  $r2 = ceil($r) - $r;  
  echo "\n" . 'r2= ' . $r2;

  $a = round($num, 1);
  if (($r2 > 0) && ($r2 < 0.5)) {
    $a = $a + 0.05; 
  }
  echo "\n" . 'a= ' . $a;
}

0
投票

在@xtofl上稍微扩展一下以允许更精确的步骤(此问题在技术上不需要)

    $step         = 0.0005;
    $multiplicand = floor($value / $step);
    $rest         = fmod($value, $step);

    $value = $step * $multiplicand;

    if ($rest > $step / 2) {
        $value += $step;
    }

0
投票
//Round to nearest 0.05
echo round ($number * 20, 0) / 20;

//Round Up to nearest 0.05
echo ceil ($number * 20) / 20;

//Round Down to nearest 0.05
echo floor ($number * 20) / 20;
© www.soinside.com 2019 - 2024. All rights reserved.