任何避免包含“9.223372036854776E18”的结果的方法
我正在编写一个程序,将大量数字转换为字符串,然后将该字符串的字符相加。它工作正常,我唯一的问题是,Java 没有将其作为普通数字,而是将我的数字转换为标准形式,这使得解析字符串变得困难。对此有什么解决办法吗?
public static void main(String ags[]) {
long nq = (long) Math.pow(2l, 1000l);
long result = 0;
String tempQuestion = Double.toString(nq);
System.out.println(tempQuestion);
String question = tempQuestion.substring(0, tempQuestion.length() - 2);
for (int count = 0; count < question.length(); count++) {
String stringResult = question.substring(count, count + 1);
result += Double.parseDouble(stringResult);
}
System.out.println(result);
I'm making a program that turns a large number into a string, and then adds the characters of that string up. It works fine, my only problem is that instead of having it as a normal number, Java converts my number into standard form, which makes it hard to parse the string. Are there any solutions to this?
public static void main(String ags[]) {
long nq = (long) Math.pow(2l, 1000l);
long result = 0;
String tempQuestion = Double.toString(nq);
System.out.println(tempQuestion);
String question = tempQuestion.substring(0, tempQuestion.length() - 2);
for (int count = 0; count < question.length(); count++) {
String stringResult = question.substring(count, count + 1);
result += Double.parseDouble(stringResult);
}
System.out.println(result);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
BigInteger 易于使用,并且您不会面临精度问题的风险。 (在这个特定的实例中,我认为不存在精度问题,因为
Math.pow(2, 1001) % 100000
返回正确的最后 5 位数字,但对于更大的数字,最终您将丢失信息.) 以下是如何使用 BigInteger:在 Java 中也是如此:
BigInteger is easy to use and you don't risk precision problems with it. (In this particular instance I don't think there is a precision problem, because
Math.pow(2, 1001) % 100000
returns the correct last 5 digits, but for bigger numbers eventually you will lose information.) Here's how you can use BigInteger:Here's the same thing in Java:
NumberFormat 的 javadoc 链接:Javadoc
Link to the javadoc for NumberFormat: Javadoc
只需将最后一行替换
为
just replace last line:
with
其他答案是正确的,您可以使用
java.text.NumberFormat
(JavaDoc) 来格式化您的输出。使用printf
也是一种格式化选项,类似于NumberFormat
。但我在这里看到了其他东西。看起来您混淆了数据类型:在nq = (long) Math.pow(2l, 1000l);
中,您已经将 Math 的双精度返回值截断为 long。那么您应该使用
long
作为数据类型而不是double
进行转换。因此使用Long.toString(long)
,这不会添加任何指数输出。使用
Long.toString(nq)
代替Double.toString(nq)
;在你的代码中。Other answers are correct, you could use a
java.text.NumberFormat
(JavaDoc) to format your output. Usingprintf
is also an option for formatting, similar toNumberFormat
. But I see something else here. It looks like you mixed up your data types: Innq = (long) Math.pow(2l, 1000l);
you are already truncating the double return value from Math to a long. Then you should use
long
as data type instead ofdouble
for the conversion. So useLong.toString(long)
, this will not add any exponent output.Use
Long.toString(nq)
instead ofDouble.toString(nq)
; in your code.正如你所说:“数字格式”。班级。
As you say: "NumberFormat". The class.