Get the sum of digits in PHP

后端 未结 13 2749
攒了一身酷
攒了一身酷 2020-11-29 10:45

How do I find the sum of all the digits in a number in PHP?

13条回答
  •  粉色の甜心
    2020-11-29 11:41

    // math before code 
    
    // base of digit sums is 9 
    
    // the product of all numbers multiplied by 9 equals 9 as digit sum
    
    $nr = 58821.5712; // any number
    
    // Initiallization 
    
    $d = array();
    
    $d = explode(".",$nr); // cut decimal digits
    
    $fl = strlen($d[1]); // count decimal digits
    
    $pow = pow(10 ,$fl); // power up for integer
    
    $nr = $nr * $pow; // make float become integer
    
    // The Code
    
    $ds = $nr % 9; // modulo of 9 
    
    if($ds == 0) $ds=9; // cancel out zeros
    
    echo $ds;
    

提交回复
热议问题