MySQL how to convert decimal value to degree, minute, second

前端 未结 3 1529
萌比男神i
萌比男神i 2021-01-27 04:54

I have a decimal value say 123.77

Now i want to convert it into corresponding degree, minute, second value using MySQ

相关标签:
3条回答
  • 2021-01-27 05:09

    The answer given by John Woo, while correct for positive values, will not give the correct results for negative values. I have adjusted his answer to take account of this.

    SET @deci = -123.77;
    SELECT SIGN(@deci)* FLOOR(ABS(@deci)) Degrees,
    FLOOR((ABS(@deci) - (FLOOR(ABS(@deci)))) * 60) Minutes,
    ((ABS(@deci) - (FLOOR(ABS(@deci)))) * 60 -
    FLOOR((ABS(@deci) - (FLOOR(ABS(@deci)))) * 60)) * 60 SECONDS
    
    0 讨论(0)
  • 2021-01-27 05:12

    Here's how,

    • The whole units of degrees will remain the same (i.e. in 121.135° longitude, start with 121°).
    • Multiply the decimal by 60 (i.e. .135 * 60 = 8.1).
    • The whole number becomes the minutes (8').
    • Take the remaining decimal and multiply by 60. (i.e. .1 * 60 = 6).
    • The resulting number becomes the seconds (6"). Seconds can remain as a decimal.
    • Take your three sets of numbers and put them together, using the symbols for degrees (°), minutes (‘), and seconds (") (i.e. 121°8'6" longitude)

    Query,

    SET @deci = 123.77;
    SELECT FLOOR(@deci) Degrees,
    
           FLOOR((@deci - (FLOOR(@deci))) * 60) Minutes,
    
           ((@deci - (FLOOR(@deci))) * 60 -
           FLOOR((@deci - (FLOOR(@deci))) * 60)) * 60 SECONDS
    

    SQLFIDDLE DEMO

    Online Conversion Tool (for checking)

    enter image description here

    0 讨论(0)
  • 2021-01-27 05:18

    Thinking out of the box, by borrowing a different Babylonian-based metric:

    mysql> SELECT TIME_FORMAT("%H°%i'%s", SEC_TO_TIME(ROUND(3600 * -1.234)));
    +-------------------------------------------------------------+
    | TIME_FORMAT("%H°%i'%s", SEC_TO_TIME(ROUND(3600 * -1.234)))  |
    +-------------------------------------------------------------+
    | -01:14:02                                                   |
    +-------------------------------------------------------------+
    mysql> SELECT TIME_FORMAT("%H°%i'%s", SEC_TO_TIME(ROUND(3600 * -123.77)));
    +--------------------------------------------------------------+
    | TIME_FORMAT("%H°%i'%s", SEC_TO_TIME(ROUND(3600 * -123.77)))  |
    +--------------------------------------------------------------+
    | -123:46:12                                                   |
    +--------------------------------------------------------------+
    

    (The ROUND is to avoid getting 3 decimal places in the answer.)

    0 讨论(0)
提交回复
热议问题