Round My number?
I have an number
$n = -5665.36
$round_set = can be : 1,10,10,100,1000
use the $round_set condition to get the $m
if $round_set = 1
$m = $n
if $round_set = 10
$m = -5660
if $round_set = 100
$m = -5600
if $round开发者_JAVA百科_set = 1000
$m = -5000
Anybody know how to round these kind of case?
Use this
intval($m/$round_set) * $round_set
http://codepad.viper-7.com/1EHFWEJ test it here.
<?php
$n = -5665.36;
$round_set = 100;
$precision = -log10($round_set);
$m = ($round_set == 1 ? $n : round($n, $precision) + $round_set);
echo $m;
?>
Wouldn't something like this work?
function rounded_nb($number, $round_set) {
return floor($number/$round_set)*$round_set;
}
For any non 0 $round_set ?
You don't need the switch, do
if($round_set > 0) {
$rounded = $round_set * floor($n / $round_set);
} else {
$rounded = $n;
}
This should pretty much do.
$rs1 = max(1, $round_set);
$m = $rs1 * floor($n / $rs1);
However a 1,10,100,... valued $round_set
might make more sense.
Why not take advantage of PHP's round
$m = round($n, ($round_set == 0 ? 0 : -1 * log10($round_set)) );
Edit: Corrected edge-case of log10(0)
.
Edit 2: Corrected the precision.
精彩评论