user2029890
user2029890

Reputation: 2713

php strip leading zeros and 0 decimal values

This falls into the category of 'I'm sure there is a cleaner way to do this' although it works perfectly well. Maybe some kind of function.

I have lists of values such as 01.0, 09.5, 10.0, 11.5,

I want the values to always exclude the leading 0 and only keep the decimal portion if it it contains a .5. There will never be any other decimal value. My current code is:

$data = '09.5'; //just an example value

if (substr($data,0,1) == '0' ) {
    $data = substr($data, 1);
}
if (stripos($data, '.0') !== FALSE ) {
    $data = str_replace('.0','',$data);
}
print $data;

Upvotes: 3

Views: 2695

Answers (1)

John Conde
John Conde

Reputation: 219804

Just cast it to a float:

$data = '09.5';
echo (float) $data; // 9.5

$data = '09.0';
echo (float) $data; // 9

$data = '010';
echo (float) $data;  // 10

Demo

You can also use floatval()

echo floatval($data);

Upvotes: 4

Related Questions