mysql : turn fraction strings into number

前端 未结 3 1040
隐瞒了意图╮
隐瞒了意图╮ 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:26

    I think this isn't something you should do in a query, but rather calculate it when it is stored and save the calculated value in the table next to its text value.

    But if you want to, you can use some string functions to slice up the value and the do the math yourself:

    select
      x.Multiplier / x.Divider as Result
    from
        (select
          cast( substr( t.String, 
                        1, 
                        locate('/', t.String) - 1) 
                as decimal) 
            as Multiplier,
          cast( substr( t.String, 
                        locate('/', t.String) + 1, 
                        locate( ' ', 
                                concat(t.String, ' '))) 
                as decimal) 
            as Divider
        from
          YourTable t) x
    

    Note however, that this may cause trouble if the data is 'invalid'. If it says '0/0 km', it may fail, if it contains 'no data here' it may fail as well.

    0 讨论(0)
  • 2021-01-24 09:30

    The above didn't quite work for me so came up with this which does. The query works for '10', '3/4' and '10 3/4'. Obviously you should replace the constructed rows at the bottom with your string or a selected value from a table:

    SELECT 
        IF (
            LOCATE(' ',fraction) > 0 OR LOCATE('/',fraction) = 0,
            SUBSTRING_INDEX(SUBSTRING_INDEX(fraction,'/','1'),' ','1')
            ,0
        ) AS `integer`,
        IF (
            LOCATE('/',fraction) > 0,
            SUBSTRING_INDEX(SUBSTRING_INDEX(fraction,'/','1'),' ','-1'),
            0
        ) AS numerator,
        SUBSTRING_INDEX(fraction,'/','-1') AS denominator,
        (SELECT `integer`) + ((SELECT numerator) / (SELECT denominator)) AS `decimal`
    FROM (
        SELECT '10 3/4' AS fraction
        UNION SELECT '10'
        UNION SELECT '3/4'
    ) t;
    
    0 讨论(0)
  • 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;
      }
    }
    
    0 讨论(0)
提交回复
热议问题