Cesar Bielich
Cesar Bielich

Reputation: 4945

format number if not a whole number show with decimal other wise show whole number

Let's say I have 2 numbers like so

1.50
2.00

I want to format the number so that

1.50 will show as 1.5
2.00 will show as 2

Basically if it is not a whole number then show that with ending 0's removed and if it is a whole number to show whole. I was trying number_format('2.00', 2); but that of course keeps the decimals. I was hoping there was a easy way to do this.

Upvotes: 0

Views: 57

Answers (2)

Sol
Sol

Reputation: 344

Try casting both strings to floats:

echo (float)'1.50';
// => 1.5
echo (float)'2.00';
// => 2

Try it online!

Upvotes: 1

Andreas
Andreas

Reputation: 23958

Multiply the number with 1 and it will remove any trailing zeros.

$arr = ["1.50","2.00"];

foreach($arr as $v){
   echo $v*1 . PHP_EOL;
}
//1.5
//2

Upvotes: 2

Related Questions