java 写一个经纬度转换
时间: 2024-05-11 22:18:15 浏览: 157
以下是一个 Java 程序,可以将经纬度转换为度分秒表示:
```java
import java.text.DecimalFormat;
public class CoordinateConverter {
public static void main(String[] args) {
double lat = 31.2304; // 纬度
double lng = 121.4737; // 经度
String latStr = convertToDMS(lat);
String lngStr = convertToDMS(lng);
System.out.println("纬度:" + latStr);
System.out.println("经度:" + lngStr);
}
/**
* 将经度或纬度转换为度分秒表示
* @param coordinate 经度或纬度
* @return 度分秒表示的字符串
*/
public static String convertToDMS(double coordinate) {
double degrees = Math.floor(coordinate); // 度
double tmp = (coordinate - degrees) * 60;
double minutes = Math.floor(tmp); // 分
double seconds = (tmp - minutes) * 60; // 秒
DecimalFormat df = new DecimalFormat("0.00"); // 保留两位小数
String dmsStr = (int) degrees + "°" + (int) minutes + "'" + df.format(seconds) + "\"";
return dmsStr;
}
}
```
输出结果为:
```
纬度:31°13'49.44"
经度:121°28'25.32"
```
该程序中的 `convertToDMS` 方法接收一个经度或纬度作为参数,返回一个度分秒表示的字符串。具体实现过程是先获取整数部分作为度数,然后将小数部分乘以 60,再分别取整得到分和秒数,最后将它们拼接成字符串。使用 `DecimalFormat` 对秒数进行保留两位小数。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)