android - 如何在 Java 中将 double 舍入到小数点后两位?

标签 android format decimal coordinates rounding

我目前正在尝试从某个位置检索纬度和经度值。当我使用以下代码将位置转换为整数值时:

    LocationManager locMan;
    Location location;
    String towers;
    private static double lat;
    private static double lon;

    locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);          
    Criteria crit = new Criteria();

    towers = locMan.getBestProvider(crit, false);
    location = locMan.getLastKnownLocation(towers);                 

        if (location != null)
        {                   

            lat = (int) (location.getLatitude() * 1E6);
            lon = (int) (location.getLongitude() * 1E6);
            GeoPoint ourLocation = new GeoPoint(lati, longi);
            OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String", "2nd String");
            CustomPinpoint custom = new CustomPinpoint(d, MainMap.this);
            custom.insertPinpoint(overlayItem);
            overlayList.add(custom);
            overlayList.clear();    

            lat = (double) lat;             
            lon = (double) lon; 

            System.out.println("Lat is  " + lat);
            System.out.println("Longi is  " + lon);
        }
        else
        {
            System.out.println("Location is null! " + towers);
            Toast.makeText(MainMap.this, "Couldn't get provider", Toast.LENGTH_SHORT).show();                   
        }

返回格式为0.000000

lat is 5.494394
long is -7.724457

我怎样才能以 00.000000 的格式取回它

我尝试了 DecimalFormat、Math.Round 和我在 Stack Overflow 上找到的各种其他解决方案,但仍然得到相同的结果。请帮忙!

最佳答案

你试过这个吗:

DecimalFormat sf = new DecimalFormat("00.000000");
String s = sf.format(5.494394);
System.out.println(s); //prints 05.494394

编辑

根据你的新问题,你为什么不这样做:

double latitude = location.getLatitude();
double longitude = location.getLongitude();
GeoPoint ourLocation = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
//....
System.out.println("Lat is  " + latitude);
System.out.println("Longi is  " + longitude);

关于android - 如何在 Java 中将 double 舍入到小数点后两位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9889569/

相关文章:

python - 无法导入 Decimal 模块

android - 权限拒绝 : opening provider

java - 某些设备上的错误 - 找不到类 'com.google.android.gms.measurement.internal.zzz'

JavaFX 表格 View : format one cell based on the value of another in the row

matlab - 在处理二进制数时,如何从 char 格式转换为 double 格式?

php - 定点类型 - "exact value or not"?

Java将字节数组转换为十六进制字节数组

android - 手势 - 手指运动时显示坐标

AndroidStudio gradle 构建锁定在 :app:compileDebugJavaWithJavac using Room

java - 帕斯卡三角形的格式