-1
$f = sprintf ("%.1f",$per);
echo "You hit".$f."

By this code i can show only one digit after floating point.But when my result is 100%,then it shows 100.0%. I want to show 100%. how could i do this????

Alma Do
  • 37,009
  • 9
  • 76
  • 105
Mak Reza
  • 107
  • 1
  • 1
  • 8

2 Answers2

5

The easiest way to do this is to cast resulting string into float again after formatting, i.e.:

$f=100.44;
$g=100;
var_dump((float)sprintf('%.1f', $f));//100.4
var_dump((float)sprintf('%.1f', $g));//100
Alma Do
  • 37,009
  • 9
  • 76
  • 105
  • I'm working with percentage.I want to show 100% when it is only 100.0%. – Mak Reza Aug 26 '13 at 07:39
  • $per = $ok*100/7; $f = sprintf ("%.1f",$per); echo "You hit ".$ok." correct out of 7 Questions ( ".$f."% ) Correct"; Plz correct this code.When the percentage will 100.0%, then I want to show only 100%. – Mak Reza Aug 26 '13 at 07:58
0
$per = 100;
$f = sprintf ("%.1f",$per);
$rounded = round($f, 1);
echo $rounded;
Leo T Abraham
  • 2,407
  • 4
  • 28
  • 54