0

How to echo number format like this using php ?

0.50 echo to 0.5
1.00 echo to 1
1.50 echo to 1.5
1.95 echo to 1.95

I tried to use number_format , ceil , floor , round But not work.

How can i do that ?

Thank you for help.

  • `echo number_format(0.50, 1)` – aldrin27 Nov 04 '15 at 05:32
  • 2
    Possible duplicate of [How can I format the number for only showing 1 decimal place in php?](http://stackoverflow.com/questions/4622328/how-can-i-format-the-number-for-only-showing-1-decimal-place-in-php) – aldrin27 Nov 04 '15 at 05:34

6 Answers6

1

It's really silly, but you can simply add 0 to get this effect.

echo "0.50" + 0;
echo "1.00" + 0;

Example

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • 1
    You can find the above answer here, http://stackoverflow.com/questions/14531679/remove-useless-zero-digits-from-decimals-in-php – Niranjan N Raju Nov 04 '15 at 05:33
1

This can do a trick:

<?php 
$string = "1.50";
echo (float)$string;
?>

This gives

1.5

Suyog
  • 2,472
  • 1
  • 14
  • 27
1

Simply use floatval function instead like as

echo floatval(0.50);

Demo

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
0

You can also do like this :

echo +'1.00';
echo +'0.50';
Krishna Gupta
  • 695
  • 4
  • 15
0

try this function

<?php 
$data = "1.00";    
$arr = explode(".",$data);
$formated_nunber=formatNumber($arr);


function formatNumber($arr){
    if($arr[1]==00){ 
      $finalStr=$arr[0];
      return $finalStr;
}
else if(substr($arr[1],-1)==0){
    $arr[1]=rtrim($arr[1],substr($arr[1],-1));
    $finalStr=implode(".",$arr);
    return $finalStr;
}else{
    $finalStr=implode(".",$arr);
    return $finalStr;
}
}   
echo "<pre>";print_r($formated_nunber);
//echo $whatIWant;

?>
PRANAV
  • 629
  • 4
  • 13
0

Use number_format(0.50, 1). That will do the trick.

Ali Zia
  • 3,825
  • 5
  • 29
  • 77
  • Code-only answers are not as helpful as answers that have working code plus helpful explanations. In this case, it would be worthwhile explaining this answer to a 5 year old. – Somnath Muluk Nov 05 '15 at 05:48