Java Math.pow()舍入错误 [英] Java Math.pow() Rounding Error

查看:97
本文介绍了Java Math.pow()舍入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了(我怀疑是)舍入错误。

I'm having trouble with (what I suspect is) a rounding error.

我有一个字符串, 0.686357E-01 ,我正在尝试将其转换为双精度。我已经可以使用 Pattern.split()函数对其进行拆分,并且可以很好地捕获基数和指数值。但是,一旦我尝试将它们适当地相乘,就会得到以下结果: 0.06863570000000001

I have a string, 0.686357E-01, which I'm trying to convert to a double. I've been able to split it up using the Pattern.split() function, and I'm capturing the base and the exponent values just fine. However, once I try to multiply them appropriately, I get this as a result: 0.06863570000000001.

这与我的相关代码:

pattern = Pattern.compile("E\\+?");
String[] number = pattern.split(string);

double base = Double.parseDouble(number[0]);
int exponent = Integer.parseInt(number[1]);

number= base*Math.pow(10, exponent);

那么,如何避免舍入错误? (有很多方法可以解决,但是,如果有可能,那么我想知道如何解决该问题)。

So, how do I avoid the rounding error? (There are ways that I can work around it, but if it's possible to do, then I'd like to know how to fix the issue)

谢谢。

推荐答案

您不需要拆分它, Double.parseDouble 可以处理

You don't need to split it, Double.parseDouble can handle those kinds of numbers just fine.

double number = Double.parseDouble("0.686357E-01");

看到?可行!

这篇关于Java Math.pow()舍入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆