1

hello i'm trying to find %. first i found the seconds

 $tm=sum_the_time($d_duration); 
 $d_seconds='0';
 list($hour,$minute,$second) = explode(':', $tm);
    $d_seconds += $hour*3600;
    $d_seconds += $minute*60;
    $d_seconds += $second;


     $total_second=$c_seconds+$p_seconds+$t_seconds+$b_seconds+$d_seconds;

 $c_seconds=$c_seconds*100/$total_second;
 $p_seconds=$p_seconds*100/$total_second;
 $t_seconds=$t_seconds*100/$total_second;
 $b_seconds=$b_seconds*100/$total_second;
 $d_seconds=$d_seconds*100/$total_second;

 echo $c_seconds;

the result is 10.754504504505, how would I print this code like 10.7

Sara
  • 8,174
  • 1
  • 35
  • 52

3 Answers3

1

You can try using printf() function:

printf("%.1f", $c_seconds);

Or, number_format():

echo number_format( $c_seconds, 1 );

These two functions will round your number (will return 10.8 in your example), so, if you want to just truncate to the first decimal place (result to be equal to 10.7), you can use the following:

echo substr($c_seconds, 0, strpos($c_seconds, ".") + 2);

Actually, you can use the solutions from this question to better use number_format() and get your desired result.

Community
  • 1
  • 1
andrux
  • 2,587
  • 3
  • 20
  • 30
0
echo sprintf('%0.1f', $c_seconds);

relevant docs here: http://php.net/sprintf

Marc B
  • 348,685
  • 41
  • 398
  • 480
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` in any code for any reason -- it should be `printf()` without `echo` every time. – mickmackusa Apr 09 '22 at 02:31
0

http://php.net/manual/en/function.number-format.php numberformat is propably what you are looking for.

ZeissS
  • 11,349
  • 4
  • 33
  • 49
  • [Are answers that just contain links elsewhere really "good answers"?](https://meta.stackexchange.com/q/8231/352329) – mickmackusa Apr 09 '22 at 02:31