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.

2

6 Answers 6

1

Simply use floatval function instead like as

echo floatval(0.50);

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

you can also use typecasting instead of functions: (float) $value;. This is little faster than floatval($value)
Yes you're right but than can be the tedious task to place it all over those strings @ling.s
1

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

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

Example

1 Comment

You can find the above answer here, stackoverflow.com/questions/14531679/…
1

This can do a trick:

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

This gives

1.5

Comments

0

You can also do like this :

echo +'1.00';
echo +'0.50';

Comments

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;

?>

Comments

0

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.