gpt4 book ai didi

java - 意外的 DecimalFormat 输出 - Java

转载 作者:行者123 更新时间:2023-11-30 06:35:25 25 4
gpt4 key购买 nike

我正在上 Java 类(class),并且正在为我的作业使用 Tsubo 计算器。我通常不会问有关堆栈溢出的问题,所以如果这看起来很基本,请原谅我。我在这里做了一些搜索并尝试了一些解决方案,但没有一个对我的情况有效。我将在下面复制部分转化

```
System.out.println("You have chosen to convert square feet to Tsubo");
System.out.println("Please enter the total sqft you are looking to convert");

sqftInput = keyboard.nextInt();

// Double is converted to string so out put remains an object of the same data type

sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");


sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + sqftResultAsString + " Tsubo"); `

当我这样做时,它告诉我无法格式化 double 值,该类型不适用于 DecimalFormat 的参数。

当我将其更改为如下所示时(有问题的行被注释掉)

' System.out.println("您已选择将平方英尺转换为坪"); System.out.println("请输入您要转换的总平方英尺");

        sqftInput = keyboard.nextInt();

// Double is converted to string so out put remains an object of the same data type
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");


//sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + sqftFormatted + " Tsubo");

程序编译并运行,当我使用 5238 作为输入数字时,我的输出如下所示 --> 5238.0 等于:java.text.DecimalFormat@674dc Tsubo

而不是实际显示答案 325.07。

我还尝试使用 stringFormat 使用一些正则表达式格式,但最终出现非法格式异常。

长话短说,我想要实现的是格式化为小数点后两位的输出,然后转换为系统输出作为答案的字符串。我缺少什么?此十进制格式是否会自动将其转换为字符串对象?

最佳答案

DecimalFormat 用于生成格式化的String。如果直接打印它,它将显示其( kind of, it's called idenity hashcode )内存地址,因为这就是 DecimalFormat.toString() 的作用。

相反,您应该使用它来生成输出字符串并直接打印。

如下:

 sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
String out = sqftFormatted.format(sqftResult); // or whatever you want to print

//sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + out + " Tsubo");

See docs for more details

关于java - 意外的 DecimalFormat 输出 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45268149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com