Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly remove leading zeroes with decimals like 0.1

Tags:

php

I aim to remove leading zeros like this:

echo ltrim(000.1, '0'); // .1 (should end up as 0.1)
echo ltrim(0, '0'); // empty (should end up as 0)
echo ltrim(00005.5, '0'); // 5.5 (correct)

Using ltrim() works fine with values like 00005.5 but doesn't work with 0.1 as 0 (as you would expect by the logic).

My question is, how can I remove leading zeros in values like 0.5 and avoid trimming value if it is 0?

like image 760
Henrik Petterson Avatar asked Nov 22 '25 21:11

Henrik Petterson


1 Answers

Just multiply it with 1 and php will cast it to float.

echo "000.1"*1 . "\n";  //0.1
echo "0"*1 . "\n";      //0 
echo "00005.5"*1 . "\n";//5.5

https://3v4l.org/mnN56

Or float cast it

echo (float)"000.1" . "\n";
echo (float)"0" . "\n";
echo (float)"00005.5" . "\n";
like image 94
Andreas Avatar answered Nov 25 '25 10:11

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!