How to find the place value for the given decimal value through php?

*爱你&永不变心* 提交于 2019-12-11 10:04:42

问题


I'm not so familiar with php, but i know we could find the place value of a given number through php. For example if the input is 23.56 it should echo 2 - Tens, 3 - Ones, 5 - Hundredths, 6 - Thousandths.

Any idea would be appreciated. :) please help.


回答1:


Try

$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 



回答2:


  <?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";
}
?>



回答3:


Another method:

$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);



回答4:


Answer for all writers:

1) Dont use for in php! Dont use! Use foreach but dont use for! Why? php stored all array keys as STRING its very slow!

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

2) Your solutions in three lines:

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;

Of course this function not check input parameters - this example. But example return valid result for all unsigned float or decimal numbers between 10 and 99.99



来源:https://stackoverflow.com/questions/25801703/how-to-find-the-place-value-for-the-given-decimal-value-through-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!