我想根据以下规则删除尾随零:
示例:
我考虑过以下事项:
if (substr($number, -2) == '00') return substr($number, 0, 4);
if (substr($number, -1) == '0') return substr($number, 0, 5);
return $number;
有没有更好的方法呢?
答案 0 :(得分:12)
我认为这应该有效:
return preg_replace('/0{1,2}$/', '', $number);
$strings = array ('1.4000', '1.4100', '1.4130', '1.4136', '1.4001', '1.0041');
foreach ($strings as $number) {
echo "$number -> " . preg_replace('/0{0,2}$/', '', $number) . "\n";
}
产地:
1.4000 -> 1.40
1.4100 -> 1.41
1.4130 -> 1.413
1.4136 -> 1.4136
1.4001 -> 1.4001
1.0041 -> 1.0041
答案 1 :(得分:0)
这是Barmar解决方案的变体,即使输入字符串并不总是精确到4位小数,它也能正常工作。它不会添加缺失的零,但它不会剥离任何超过它。
return preg_replace('/(\.[0-9]{2,}?)0*$/', '$1', $number);
举个例子:
$strings = array(
'1.4000',
'1.4100',
'1.4130',
'1.4136',
'1.0',
'1.00',
'1.000',
'10000',
);
foreach ($strings as $number) {
$fixed = preg_replace('/(\.[0-9]{2,}?)0*$/', '$1', $number);
echo "{$number} -> {$fixed}\n";
}
输出:
1.4000 -> 1.40
1.4100 -> 1.41
1.4130 -> 1.413
1.4136 -> 1.4136
1.0 -> 1.0
1.00 -> 1.00
1.000 -> 1.00
10000 -> 10000
答案 2 :(得分:0)
现在有一些完全不同的东西......
<?php
$crlf = "\n";
$input = array('1.4000', '1.4300', '1.2340', '1.4012', '1.0034', '1.2', '1.23456');
foreach ($input as $in) {
for($n = 4; $n>2; $n--) {
$f1 = (float)round($in, $n);
$f2 = (float)round($in, $n-1);
if ($f1 !== $f2) break;
}
echo "for in = ".$in." out is ".number_format($in, $n) . $crlf;
}
?>
输出:
for in = 1.4000 out is 1.40
for in = 1.4300 out is 1.43
for in = 1.2340 out is 1.234
for in = 1.4012 out is 1.4012
for in = 1.0034 out is 1.0034
for in = 1.2 out is 1.20
for in = 1.23456 out is 1.2346
请注意,对于格式正确的数字(十进制后正好四位数),这将表现得如预期的那样,但是当数字格式不正确时,它仍会表现出来。不是所要求的 - 但是拥有一个强大的解决方案通常比最简单的解决方案更好......