PHP:获取小数位数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2430084/
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
PHP: get number of decimal digits
提问by Erwin
Is there a straightforward way of determining the number of decimal places in a(n) integer/double value in PHP? (that is, without using explode)
有没有一种直接的方法可以确定 PHP 中(n)整数/双精度值的小数位数?(即,不使用explode)
回答by ghostdog74
$str = "1.23444";
print strlen(substr(strrchr($str, "."), 1));
回答by Allyn
You could try casting it to an int, subtracting that from your number and then counting what's left.
您可以尝试将其转换为 int,从您的数字中减去它,然后计算剩余的数量。
回答by Kris
function numberOfDecimals($value)
{
if ((int)$value == $value)
{
return 0;
}
else if (! is_numeric($value))
{
// throw new Exception('numberOfDecimals: ' . $value . ' is not a number!');
return false;
}
return strlen($value) - strrpos($value, '.') - 1;
}
/* test and proof */
function test($value)
{
printf("Testing [%s] : %d decimals\n", $value, numberOfDecimals($value));
}
foreach(array(1, 1.1, 1.22, 123.456, 0, 1.0, '1.0', 'not a number') as $value)
{
test($value);
}
Outputs:
输出:
Testing [1] : 0 decimals
Testing [1.1] : 1 decimals
Testing [1.22] : 2 decimals
Testing [123.456] : 3 decimals
Testing [0] : 0 decimals
Testing [1] : 0 decimals
Testing [1.0] : 0 decimals
Testing [not a number] : 0 decimals
回答by skips
I used the following to determine whether a returned value has any decimals (actual decimal values, not just formatted to display decimals like 100.00):
我使用以下内容来确定返回值是否有任何小数(实际的十进制值,不仅仅是格式化为显示小数,如 100.00):
if($mynum - floor($mynum)>0) {has decimals;} else {no decimals;}
回答by Sergey
<?php
test(0);
test(1);
test(1.234567890);
test(-123.14);
test(1234567890);
test(12345.67890);
function test($f) {
echo "f = $f\n";
echo "i = ".getIntCount($f)."\n";
echo "d = ".getDecCount($f)."\n";
echo "\n";
}
function getIntCount($f) {
if ($f === 0) {
return 1;
} elseif ($f < 0) {
return getIntCount(-$f);
} else {
return floor(log10(floor($f))) + 1;
}
}
function getDecCount($f) {
$num = 0;
while (true) {
if ((string)$f === (string)round($f)) {
break;
}
if (is_infinite($f)) {
break;
}
$f *= 10;
$num++;
}
return $num;
}
Outputs:
输出:
f = 0
i = 1
d = 0
f = 1
i = 1
d = 0
f = 1.23456789
i = 1
d = 8
f = -123.14
i = 3
d = 2
f = 1234567890
i = 10
d = 0
f = 12345.6789
i = 5
d = 4
回答by David says reinstate Monica
Something like:
就像是:
<?php
$floatNum = "120.340304";
$length = strlen($floatNum);
$pos = strpos($floatNum, "."); // zero-based counting.
$num_of_dec_places = ($length - $pos) - 1; // -1 to compensate for the zero-based count in strpos()
?>
This is procedural, kludgy and I wouldn't advise using it in production code. But it should get you started.
这是程序性的,笨拙的,我不建议在生产代码中使用它。但它应该让你开始。
回答by Jeremy Worboys
I needed a solution that works with various number formats and came up with the following algorithms:
我需要一个适用于各种数字格式的解决方案,并提出了以下算法:
// Count the number of decimal places
$current = $value - floor($value);
for ($decimals = 0; ceil($current); $decimals++) {
$current = ($value * pow(10, $decimals + 1)) - floor($value * pow(10, $decimals + 1));
}
// Count the total number of digits (includes decimal places)
$current = floor($value);
for ($digits = $decimals; $current; $digits++) {
$current = floor($current / 10);
}
Results:
结果:
input: 1
decimals: 0
digits: 1
input: 100
decimals: 0
digits: 3
input: 0.04
decimals: 2
digits: 2
input: 10.004
decimals: 3
digits: 5
input: 10.0000001
decimals: 7
digits: 9
input: 1.2000000992884E-10
decimals: 24
digits: 24
input: 1.2000000992884e6
decimals: 7
digits: 14
回答by simhumileco
Solution
解决方案
$num = "12.1234555";
print strlen(preg_replace("/.*\./", "", $num)); // 7
Explanation
解释
Pattern .*\.means all the characters before the decimal point with its.
模式.*\.表示小数点前的所有字符及其。
In this case it's string with three characters: 12.
在这种情况下,它是包含三个字符的字符串: 12.
preg_replacefunction converts these cached characters to an empty string ""(second parameter).
preg_replace函数将这些缓存的字符转换为空字符串""(第二个参数)。
In this case we get this string: 1234555
在这种情况下,我们得到这个字符串: 1234555
strlenfunction counts the number of characters in the retained string.
strlen函数计算保留字符串中的字符数。
回答by Ian
If you want readability for the benefit of other devs, locale safe, use:
如果为了其他开发人员的利益而希望可读性,区域设置安全,请使用:
function countDecimalPlacesUsingStrrpos($stringValue){
$locale_info = localeconv();
$pos = strrpos($stringValue, $locale_info['decimal_point']);
if ($pos !== false) {
return strlen($stringValue) - ($pos + 1);
}
return 0;
}
see localeconv
回答by Robert James Reese
Here's a function that takes into account trailing zeroes:
这是一个考虑尾随零的函数:
function get_precision($value) {
if (!is_numeric($value)) { return false; }
$decimal = $value - floor($value); //get the decimal portion of the number
if ($decimal == 0) { return 0; } //if it's a whole number
$precision = strlen($decimal) - 2; //-2 to account for "0."
return $precision;
}

