如何去除 PHP 中的尾随零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5149129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to strip trailing zeros in PHP
提问by nhunston
Hi could anyone give me an explanation (and maybe an example) as to how would I go about stripping the trailing zeros from a number using PHP.
嗨,任何人都可以给我一个解释(也许是一个例子)关于我将如何使用 PHP 从数字中去除尾随零。
For example:
例如:
"Lat":"37.422005000000000000000000000000","Lon":"-122.84095000000000000000000000000"
Would be turned in to:
将变成:
"Lat":"37.422005","Lon":"-122.84095"
I am trying to strip the zeros to make it more readable. I tried using str_replace()
but this replaced the zeros inside the number too (doh).
我正在尝试去除零以使其更具可读性。我尝试使用,str_replace()
但这也替换了数字内的零(doh)。
Thanks =D
谢谢=D
回答by RobertPitt
Forget all the rtrims, and regular expressions, coordinates are floats and should be treated as floats, just prepend the variable with (float)
to cast it from a string to a float:
忘记所有的 rtrims 和正则表达式,坐标是浮点数,应该被视为浮点数,只需在变量前面加上(float)
以将其从字符串转换为浮点数:
$string = "37.422005000000000000000000000000";
echo (float)$string;
output:
输出:
37.422005
The actual result you have are floats but passed to you as strings due to the HTTP Protocol, it's good to turn them back into thier natural form to do calculations etc on.
您拥有的实际结果是浮点数,但由于 HTTP 协议而作为字符串传递给您,最好将它们转换回它们的自然形式以进行计算等。
Test case: http://codepad.org/TVb2Xyy3
测试用例:http: //codepad.org/TVb2Xyy3
Note: Regarding the comment about floating point precision in PHP, see this: https://stackoverflow.com/a/3726761/353790
注意:关于 PHP 中浮点精度的评论,参见:https: //stackoverflow.com/a/3726761/353790
回答by jweyrich
Try with rtrim:
尝试使用rtrim:
$number = rtrim($number, "0");
If you have a decimal number terminating in 0's (e.g. 123.000), you mayalso want to remove the decimal separator, which may be different depending on the used locale. To remove it reliably, you may do the following:
如果您有一个以 0 结尾的十进制数(例如 123.000),您可能还想删除小数点分隔符,这可能会因使用的语言环境而有所不同。要可靠地删除它,您可以执行以下操作:
$number = rtrim($number, "0");
$locale_info = localeconv();
$number = rtrim($number, $locale_info['decimal_point']);
This of course is not a bullet-proof solution, and may not be the best one. If you have a number like 12300.00, it won't remove the trailing 0's from the integer part, but you can adapt it to your specific need.
这当然不是万无一失的解决方案,也可能不是最好的解决方案。如果你有一个像 12300.00 这样的数字,它不会从整数部分删除尾随的 0,但你可以根据你的特定需要调整它。
回答by Okonomiyaki3000
You'll run into a lot of trouble if you try trimming or other string manipulations. Try this way.
如果您尝试修剪或其他字符串操作,您会遇到很多麻烦。试试这个方法。
$string = "37.422005000000000000000000000000";
echo $string + 0;
Outputs:
输出:
37.422005
回答by Farray
You can also use floatval(val);
.
您也可以使用floatval(val);
.
<?php
echo floatval( "37.422005000000000000000000000000" );
?>
results in
结果是
37.422005
37.422005
回答by mpen
Most of these solutions will trim significant digits in numbers such as "100" (no trailing decimal). Here's a simple solution that doesn't have this problem:
这些解决方案中的大多数将修剪数字中的有效数字,例如“100”(无尾随小数)。这是一个没有这个问题的简单解决方案:
function TrimTrailingZeroes($nbr) {
if(strpos($nbr,'.')!==false) $nbr = rtrim($nbr,'0');
return rtrim($nbr,'.') ?: '0';
}
I think that covers all the different scenarios.
我认为这涵盖了所有不同的场景。
>>> TrimTrailingZeroes('0')
=> "0"
>>> TrimTrailingZeroes('01')
=> "01"
>>> TrimTrailingZeroes('01.0')
=> "01"
>>> TrimTrailingZeroes('01.01')
=> "01.01"
>>> TrimTrailingZeroes('01.010')
=> "01.01"
>>> TrimTrailingZeroes('.0')
=> "0"
>>> TrimTrailingZeroes('.1')
=> ".1"
>>> TrimTrailingZeroes('.10')
=> ".1"
>>> TrimTrailingZeroes('3141592653589793.238462643383279502880000000000000000000000000000')
=> "3141592653589793.23846264338327950288"
回答by Warren Sergent
In my case, I did the following, extending other answers here:
就我而言,我执行了以下操作,并在此处扩展了其他答案:
rtrim((strpos($number,".") !== false ? rtrim($number, "0") : $number),".");
Because I also had to remove the decimal if a whole number was being shown
因为如果显示整数,我还必须删除小数
As an example, this will show the following numbers
例如,这将显示以下数字
2.00, 1.00, 28.50, 16.25
As
作为
2, 1, 28.5, 16.25
Rather than
而不是
2., 1., 28.5, 16.25
Which, to me, is not showing them correctly.
对我来说,这没有正确显示它们。
Latest edit also stops numbers such as "100" from being rtrim'ed to 1, by only trimming the rightmost 0's if a decimal is encountered.
最新编辑还通过仅在遇到小数时修剪最右边的 0 来阻止诸如“100”之类的数字被 rtrim'ed 为 1。
回答by scott klarr
If you want to strip the excess zeros away from the end but only to a certain decimal place, this is a useful expression to do just that (for example 0.30000 will show 0.30 and 0.0003000 will show 0.0003).
如果您想从末尾去除多余的零,但只保留到某个小数位,这是一个有用的表达式(例如 0.30000 将显示 0.30,0.0003000 将显示 0.0003)。
preg_replace("/(?<=\.[0-9]{2})[0]+$/","",$number);
Of course the {2} controls the decimal place limit.
当然,{2} 控制小数位限制。
回答by mpen
Trims trailing zeroes, but only after the decimal place -- we wouldn't want to convert 100 -> 1, for example. It will also strip the period if only zeros follow it.
修剪尾随零,但只在小数位之后——例如,我们不想转换 100 -> 1。如果后面只有零,它也会去掉句号。
function trim_zeros($str) {
if(!is_string($str)) return $str;
return preg_replace(array('`\.0+$`','`(\.\d+?)0+$`'),array('',''),$str);
}
回答by Devon
If you want a solution that accepts a minimum and maximum amount of decimal places, this should work:
如果您想要一个接受最小和最大小数位数的解决方案,这应该有效:
/**
* Displays up to 4 decimal places, with a minimum of 2 decimal places, trimming unnecessary zeroes
*
* @param mixed $number
* @param int $minimumDecimals
* @param int $maximumDecimals
* @return string
*/
function rate_format($number, int $minimumDecimals = 2, int $maximumDecimals = 4): string
{
$formatted = number_format($number, $maximumDecimals, '.', ',');
$minimumLength = strpos($formatted, '.') + $minimumDecimals + 1;
$extra = rtrim(substr($formatted, $minimumLength), "0");
return substr($formatted, 0, $minimumLength) . $extra;
}
// rate_format("1.2500") returns "1.25"
// rate_format("1.2525") returns "1.2525"
// rate_format("1.25256") returns "1.2526"
// rate_format("1") returns "1.00"
This is hard coded to use the US locale, but should be easily adjusted for other locales.
这是硬编码以使用美国语言环境,但应该很容易针对其他语言环境进行调整。
回答by Joe Kuan
For me, I need a further solution to convert exponential values and simple numbers like 10000 to the last non-zero significant digit
对我来说,我需要一个进一步的解决方案来将指数值和简单的数字(如 10000)转换为最后一个非零有效数字
/* Convert any value to the least significant value */
function toDecimal($val) {
// Convert any exponential sign to proper decimals
$val = sprintf("%lf", $val);
if (strpos($val, '.') !== false) {
$val = rtrim(rtrim($val, '0'), '.');
}
return $val;
}
// Test cases
echo toDecimal(1000.000) . "\n";
echo toDecimal(1E-5) . "\n";
echo toDecimal(1E+5) . "\n";
echo toDecimal(1234.56) . "\n";
echo toDecimal(1234.5700) . "\n";
echo toDecimal(1234000) . "\n";
echo toDecimal(-1e10) . "\n";
// Results
1000
0.00001
100000
1234.56
1234.57
1234000
-10000000000