I have a decimal value say 123.77
Now i want to convert it into corresponding degree
, minute
, second
value using MySQ
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
Here's how,
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)
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.)