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?
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With