3

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;
2
  • 2
    $data += 0; will strip the leading zeroes Commented Apr 9, 2014 at 17:54
  • You'll want to look at regular expressions and the preg_replace function. Commented Apr 9, 2014 at 17:54

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I suspect OP's example: there will never be any other decimal value makes me think there will be integer-like strings with leading zeros. (float) '010' is, of course, 8.
I was curious about this but 3v4l.org/INBiF confirms my suspicions that your second example still returns 9.5
My second example uses 09.0. It can't return 9.5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.