PHP: convert string to float (only if string represents a float)

前端 未结 5 904
隐瞒了意图╮
隐瞒了意图╮ 2021-01-16 08:59

I have an unknwon string that could resemble a float. In that case I want to convert it to float (for calculations), otherwise leave it as a string.

5条回答
  •  星月不相逢
    2021-01-16 09:36

    Because it hasn't been mentioned

    if(preg_match('/^\d+\.\d+$/', $string)){
       $float = (float)$string;
    }
    

    I think is_numeric is a better choice, but this works too.

    What I have above only matches floats, so they have to have the decimal. To make that optional use /^\d+(\.\d+)?$/ instead.

    • ^ start of string
    • \d+ one or more digits
    • \. the dot, literally
    • \d+ one or more digits
    • $ end of string

    For the second one /^\d+(\.\d+)?$/ it's the same as the above except with this addition:

    • (...)? optional capture group, match this pastern 0 or 1 times.

    Which it should now be obvious is what makes the decimal optional.

    Cheers!

提交回复
热议问题