mysql : turn fraction strings into number

前端 未结 3 1042
隐瞒了意图╮
隐瞒了意图╮ 2021-01-24 08:54

I have strings like... \"3/4\" and \"5/9\" and some like... \"1/2 km\" and \"3/4 degree\" stored in mysql columns.

I would like to convert them into numbers. In first c

3条回答
  •  抹茶落季
    2021-01-24 09:32

    With PHP you could do:

    // assuming $vals has the values from the database
    $converted = array();
    foreach ($vals as $key => $val) {
      preg_match("/^(\\d+)\\/(\\d+)/", $val, $matches)
      if (count($matches) > 2) {
        $numerator = (int) $matches[1];
        $denominator = (int) $matches[2];
        $converted[$key] = (float) $numerator / $denominator;
      }
    }
    

提交回复
热议问题