如何通过PHP找到给定十进制值的位置值?

时间:2014-09-12 06:00:33

标签: php numbers

我不熟悉php,但我知道我们可以通过php找到给定数字的位置值。例如,如果输入是23.56,它应该回显2 - Tens,3 - Ones,5 - Huthths,6 - Thousandths。

任何想法都会受到赞赏。 :)请帮忙。

4 个答案:

答案 0 :(得分:1)

尝试

$str = '23.56';
$strdiv = explode('.', $str);
$before = array('Tens', 'Ones');
$after = array('Hundredths', 'Thousandths');
$counter = 0;
foreach($strdiv as $v) {
  for($i=0; $i<strlen($v); $i++) {
     if(!empty($v)) {
       if($counter == 0) {
         $newarr[] = substr($v,$i, 1).' - '.$before[$i];
       }
       if($counter == 1) {
         $newarr[] = substr($v,$i, 1).' - '.$after[$i];
       }
     }
  }
  $counter++;
}
echo implode(', ',$newarr); //2 - Tens, 3 - Ones, 5 - Hundredths, 6 - Thousandths 

答案 1 :(得分:0)

  <?php
$mystring = '123.64';
$findme   = '.';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of '.' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

答案 2 :(得分:0)

另一种方法:

$num = 23.56;
$arr = array("Tens","Ones","Hundredths","Thousandths");
$num = str_replace(".","",$num);

for ($i=0;$i<strlen($num);$i++) {

        $res[] = $num[$i] ." - ".$arr[$i];
}

echo implode(', ',$res);

答案 3 :(得分:0)

回答所有作家:

1)不要在php中使用 for !别用!使用 foreach ,但不要使用 !为什么? php将所有数组键存储为 STRING 非常慢!

$arr = array('a', 'b', 'c');
var_dump($arr[0] === $arr['0']); // true

2)您的解决方案分为三行:

function humanityFloat($v) {
    $out = str_split(str_replace('.', '', sprintf('%01.2f', (float) $v)));
    array_walk($out, function(&$a, $i, $s) { $a .= ' - ' . $s[$i]; }, array('Tens', 'Ones', 'Hundredths', 'Thousandths'));
    return join(', ', $out);
}

echo humanityFloat(22) . PHP_EOL;

当然这个函数不检查输入参数 - 这个例子。但是示例返回10到99.99之间的所有无符号浮点数或十进制数的有效结果