[英]PHP: get number of decimal digits
有沒有一種直接的方法可以確定 PHP 中(n)整數/雙精度值的小數位數? (也就是說,不使用explode
)
$str = "1.23444";
print strlen(substr(strrchr($str, "."), 1));
您可以嘗試將其轉換為 int,從您的數字中減去它,然后計算剩余的數量。
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);
}
輸出:
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
更少的代碼:
$str = "1.1234567";
echo strpos(strrev($str), ".");
我需要一個適用於各種數字格式的解決方案,並提出了以下算法:
// 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);
}
結果:
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
我使用以下內容來確定返回的值是否有任何小數(實際的十進制值,不僅僅是格式化為顯示小數,如 100.00):
if($mynum - floor($mynum)>0) {has decimals;} else {no decimals;}
<?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;
}
輸出:
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
這是一個考慮尾隨零的函數:
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;
}
就像是:
<?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()
?>
這是程序性的,笨拙的,我不建議在生產代碼中使用它。 但它應該讓你開始。
$num = "12.1234555";
print strlen(preg_replace("/.*\./", "", $num)); // 7
模式.*\\.
表示小數點前的所有字符及其。
在這種情況下,它是包含三個字符的字符串: 12.
preg_replace
函數將這些緩存的字符轉換為空字符串""
(第二個參數)。
在這種情況下,我們得到這個字符串: 1234555
strlen
函數計算保留字符串中的字符數。
如果為了其他開發人員的利益而希望可讀性,區域設置安全,請使用:
function countDecimalPlacesUsingStrrpos($stringValue){
$locale_info = localeconv();
$pos = strrpos($stringValue, $locale_info['decimal_point']);
if ($pos !== false) {
return strlen($stringValue) - ($pos + 1);
}
return 0;
}
這個怎么樣?:
$iDecimals = strlen($sFull%1);
$decnumber = strlen(strstr($yourstr,'.'))-1
整數沒有十進制數字,所以答案總是零。
雙精度或浮點數是近似值。 所以他們沒有定義的十進制數字數。
一個小例子:
$number = 12.00000000012;
$frac = $number - (int)$number;
var_dump($number);
var_dump($frac);
輸出:
float(12.00000000012)
float(1.2000000992884E-10)
你可以在這里看到兩個問題,第二個數字是使用科學表示法,它不完全是 1.2E-10。
對於包含整數/浮點數的字符串,您可以搜索小數點:
$string = '12.00000000012';
$delimiterPosition = strrpos($string, '.');
var_dump(
$delimiterPosition === FALSE ? 0 : strlen($string) - 1 - $delimiterPosition
);
輸出:
int(11)
首先,我使用strpos
函數找到了小數點的位置,並將strpos
位置值增加 1 以跳過小數位。
其次,我從點 1 得到的值中減去了整個字符串長度。
第三,我使用substr
函數來獲取小數點后的所有數字。
第四,我使用了strlen
函數來獲取小數點后字符串的長度。
這是執行上述步驟的代碼:
<?php
$str="98.6754332";
echo $str;
echo "<br/>";
echo substr( $str, -(strlen($str)-(strpos($str, '.')+1)) );
echo "<br/>";
echo strlen( substr( $str, -(strlen($str)-(strpos($str, '.')+1))) );
?>
您應該始終小心不同的語言環境。 歐洲語言環境使用逗號作為千位分隔符,因此接受的答案不起作用。 請參閱下面的修訂解決方案:
function countDecimalsUsingStrchr($stringValue){
$locale_info = localeconv();
return strlen(substr(strrchr($stringValue, $locale_info['decimal_point']), 1));
}
這適用於任何數字,即使是科學記數法,精度可達小數點后 100 位。
$float = 0.0000005;
$working = number_format($float,100);
$working = rtrim($working,"0");
$working = explode(".",$working);
$working = $working[1];
$decmial_places = strlen($working);
結果:
7
冗長但無需復雜條件即可工作。
$value = 182.949;
$count = strlen(abs($value - floor($value))) -2; //0.949 minus 2 places (0.)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.