简体   繁体   中英

Number format and rounding in php

xx.01 and xx.02 go to xx.00
xx.03 and xx.04 go to xx.05
xx.06 and xx.07 go to xx.05
xx.08 and xx.09 go to xx.10
xx.11 and xx.12 go to xx.10
xx.13 and xx.14 go to xx.15

I need the below format behind the dot.

0.05 / 0.10 / 0.15/ 0.20 / 0.25 / 0.30 / 0.35 / 0.40 etc….

Can anyone give me a function in PHP to convert the number after the dot to the expected value?

function soRound($a, $to=0.05) {
  return round($a / $to) * $to ;
}

This rounds as you describe with no default second argument

ie soRound(1.07); returns 1.05

You need to round, but you can only use round to round to the nearest tenth. You want to round to the nearest twentieth. The solution is to multiply by 2, round to the nearest tenth, divide by 2, and format as needed:

$data = [0, 0.01, 0.07, 0.09, 1.56, 1.73, 3.14159];

foreach ($data as $num) {
    $num = round($num * 2, 1) / 2;
    echo number_format($num, 2) . "\n";
}

Output:

0.00
0.00
0.05
0.10
1.55
1.75
3.15

Here's a working demo .

In function form:

function roundToNearest05($num) {
    return round($num * 2, 1) / 2;
}

// or, more generically, this:

function roundTo($num = 0, $nearest = 0.05) {
    return round($num / $nearest) * $nearest;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM