将新数字添加为浮点数的最后一位数字

huangapple go评论67阅读模式
英文:

Add new number as last digit of floating point number

问题

以下是翻译好的内容:

我在Java中遇到了一个小问题,可能需要一点帮助。

假设我有一个数字 i,我想将它附加到一个双精度浮点数 val 上。
它需要的效果就像你在计算器上输入一个数字一样。

我知道如何处理整数:

double val = 7;
double i = 2;
val = val * 10;
val += i;

然后变量 val 的输出为 72,正如我所期望的。

但是我就是想不明白如何处理小数位。

假设我有 val = 2.72i = 3
我该如何使它 输出 2.723 呢?

它需要能够处理小数点后的任意数量的数字。

提前感谢你的帮助!

英文:

I could need a little bit help with a small problem I faced in Java.

So let's say I have a number i that I want to attach to a double val.
It needs to work the same as you type a number on a calculator.

I know how to do so with whole numbers:

        double val = 7;
        double i = 2;
        val = val*10;
        val += i;

Then var outputs 72, just as I wanted

But I just can't figure it out how to do so with decimal places.

Lets say I have var = 2.72 and i = 3.
How do I make it output 2.723?

It needs to work with any amount of numbers after the decimal point.

Thanks in advance!

答案1

得分: 1

你可以使用这个逻辑:(要附加的编号应为整数)

Double val = 2.34;
int p = 2;
String s = val.toString();
s = s + p;
System.out.println(s);  //字符串中的2.342
val = Double.parseDouble(s);
System.out.println(val);  //双精度浮点数中的2.342
英文:

You can use this logic : (No. to be appended should be integer)

    Double val = 2.34;
    int p = 2;
    String s = val.toString();
    s = s + p;
    System.out.println(s);  //2.342 in string
    val = Double.parseDouble(s);
    System.out.println(val);  //2.342 in double

答案2

得分: 0

System.out.println(String.valueOf(val).toString() + Math.round(i));
输出 2.723

英文:
System.out.println(String.valueOf(val).toString()+Math.round(i));

output 2.723

huangapple
  • 本文由 发表于 2020年9月12日 00:44:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63851145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定