【问题标题】:Fatal Exception: java.lang.NumberFormatException致命异常:java.lang.NumberFormatException
【发布时间】:2016-03-16 03:08:59
【问题描述】:

当我从 GPS 获得新的位置坐标并且我想对其进行格式化时,我会不时收到此异常。

这是我的代码:

    DecimalFormat decimalFormat = new DecimalFormat("0.00000");
            location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude())));
            location.setLongitude(Double.valueOf(decimalFormat.format(location.getLongitude())));

为什么会这样?我从该位置返回的纬度和经度都是双精度数。我将其格式化,将其转换为所需的格式(点后 5 位小数),然后当我尝试进行双回时,它崩溃了。为什么会这样?为什么不是每次,只是有时?

崩溃示例:

 Fatal Exception: java.lang.NumberFormatException
 Invalid double: "52,36959"

这是我使用它的地方:

Log.i("","enteredd latitude is:" + location.getLatitude());
            try{
                DecimalFormat decimalFormat = new DecimalFormat("0.00000");
                location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude()).replace(",", ".")));
                location.setLongitude(Double.valueOf(decimalFormat.format(location.getLongitude()).replace(",", ".")));
            }catch (Exception e){
                Log.e("","enteredd error deimal formating" + e.getMessage());
            }
            Log.i("","enteredd latitude is:" + location.getLatitude());

同样的事情:

location = LocationServices.FusedLocationApi.getLastLocation(PSLocationCenter.getInstance().mLocationClient);

问题:如果我这样做,它会修复它吗?

 location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude()).replace(",", ".")));

【问题讨论】:

  • location.getLongitude()location.getLongitude() 的值是多少?
  • 我不知道。我在 Fabric 上发现了崩溃。它经常使用这个,比如每分钟至少 6 次,如果打开了正确的活动,直到 60 次。我在 3 天内“只有”15 次坠毁。我所知道的是我得到:无效的双精度:“52,36959”所以我猜纬度将类似于 52,36959xxx
  • 因此解析 double 将失败,因为它包含逗号字符。
  • 我需要把逗号编辑成“.”吗?如果这是问题所在,那么为什么它不会一直崩溃?我的意思是,我应该总是得到带小数的位置
  • 位置在哪里获取数据?一些外部API?您应该了解为什么有时会得到这些似乎不是某个位置的合法值的值。

标签: android double number-formatting numberformatexception decimalformat


【解决方案1】:

您将双精度值转换为十进制格式,然后将其解析回双精度并使用从变量location 获得的相同值来设置location 的值。这其中有大量的糟糕逻辑。

location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude())));
location.setLongitude(Double.valueOf(decimalFormat.format(location.getLongitude())));

location.getLatitude 为纬度,无需设置。

需要设置小数点分隔符:

DecimalFormat decimalFormat = new DecimalFormat("0.00000");
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
decimalFormat.setDecimalFormatSymbols(dfs);

从这里:(android) decimalformat, uses comma in place of fullstop while formatting with "#.##"

还有:

获取位置。

double latitude = location.getLatitude();
double longitude = location.getLongitude();

就您的应用而言,您无需更改此设置。

只需将值传递给您需要的服务器:

String lat = decimalFormat(latitude);
String long = decimalFormat(longitude);

【讨论】:

  • 其实我愿意!我需要将纬度和经度发送到仅包含 5 位小数的服务器位置。这意味着:52.367991324 必须变为:52.36799。现在,如果您有更好的版本来执行此操作,请告诉我。我是这样做的,因为不知道经度和经度有多少小数,我不能除以得到 5 个小数
猜你喜欢
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 2017-09-13
  • 2012-07-23
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多