문제

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;
도움이 되었습니까?

해결책

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top