如何添加两个java.lang.Numbers? [英] How to add two java.lang.Numbers?

查看:87
本文介绍了如何添加两个java.lang.Numbers?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个号码。例如:

Number a = 2;
Number b = 3;
//Following is an error:
Number c = a + b;

为什么Numbers不支持算术运算?无论如何我如何在java中添加这两个数字? (当然我从某个地方得到它们,我不知道它们是整数还是漂浮等)。

Why arithmetic operations are not supported on Numbers? Anyway how would I add these two numbers in java? (Of course I'm getting them from somewhere and I don't know if they are Integer or float etc).

推荐答案

你说你不知道你的数字是整数还是浮点数...当你使用 Number 类时,编译器也不知道你的数字是否是整数,漂浮或其他一些东西。结果,像+和 - 这样的基本数学运算符不起作用;计算机不知道如何处理这些值。

You say you don't know if your numbers are integer or float... when you use the Number class, the compiler also doesn't know if your numbers are integers, floats or some other thing. As a result, the basic math operators like + and - don't work; the computer wouldn't know how to handle the values.

START EDIT

START EDIT

根据讨论情况,我想一个例子可能有所帮助。计算机将浮点数存储为两部分,即系数和指数。因此,在理论系统中,001110可能被分解为0011 10或3 2 = 9.但正整数将数字存储为二进制,因此001110也可以表示2 + 4 + 8 = 14。当你使用类 Number 时,你告诉计算机你不知道这个数字是浮点数还是int或什么,所以它知道它有001110但是它不知道这是否意味着9或14或其他一些价值。

Based on the discussion, I thought an example might help. Computers store floating point numbers as two parts, a coefficient and an exponent. So, in a theoretical system, 001110 might be broken up as 0011 10, or 32 = 9. But positive integers store numbers as binary, so 001110 could also mean 2 + 4 + 8 = 14. When you use the class Number, you're telling the computer you don't know if the number is a float or an int or what, so it knows it has 001110 but it doesn't know if that means 9 or 14 or some other value.

END EDIT

你是什么可以做的是做一点假设并转换为其中一种类型来进行数学运算。所以你可以

What you can do is make a little assumption and convert to one of the types to do the math. So you could have

Number c = a.intValue() + b.intValue();

您可能会变成

Integer c = a.intValue() + b.intValue();

如果您愿意遭受一些舍入错误,或

if you're willing to suffer some rounding error, or

Float c = a.floatValue() + b.floatValue();

如果您怀疑自己没有处理整数,并且可能存在轻微的精确度问题。或者,如果你宁愿采取一个小的性能打击而不是那个错误,

if you suspect that you're not dealing with integers and are okay with possible minor precision issues. Or, if you'd rather take a small performance blow instead of that error,

BigDecimal c = new BigDecimal(a.floatValue()).add(new BigDecimal(b.floatValue()));

这篇关于如何添加两个java.lang.Numbers?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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