tags:

views:

222

answers:

7

Hello Everybody,

I would like to solve rounding mechanism by using php4,5.2 and below (not 5.3) Currently I am doing 0.05 rounding, something like this page:

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

I try to use string to split it out and manually do adding, but not really a good solution, hoping here can find someone to solve it.

Thank for helping.

A: 

Multiply by two, then round, then divide by two.

Travis
`s/two/twenty/g`
hobbs
A: 

You basically want to map values to a grid. The grid is defined as a multiple of .05. In general, you need to find the multiplicands your value lies between.

What isn't in the table are the negative numbers. You need to decide on whether to round away from zero (symmetrical) or always in the same direction (i.e. positive).

code:

$step = .05;
$multiplicand = floor( $value / $step );
$rest = $value % $step ;
if( $rest > $step/2 ) $multiplicand++; // round up if needed
$roundedvalue = $step*$multiplicand;
xtofl
There's a division by zero on the `$rest = ` line.
random
@e.c.ho: how can that be if `$step` isn't zero?
xtofl
Ran the code and that's the error message that came flying back.
random
+2  A: 

use this function

function rndfunc($x){
  return round($x * 2, 1) / 2;
}
thephpdeveloper
You end up with only one number after the decimal if it ends in zero (0).
random
then you can just simply format it with number_format()
thephpdeveloper
sprintf('%0.2f', rndfunc($x));
nathan
A: 

Divide by 0.05, round to nearest integer, then multiply by 0.05.

Craig McQueen
A: 

Hint:-

$input1 = 24.05;

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

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

$ouput = $tenpcnt / 20;

echo $ouput; // 2.40

James Anderson
A: 
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";
Abu Aqil
A: 

I'm sure there are more elegant solutions, but this appears to suit the task:

<?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;
}
nathan
Mauris wins - I figured there was a simpler method. (-:
nathan