有没有更好的方法来处理双精度数学计算?

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

Is there a better way handle maths calculations with doubles?

问题

我正在构建一个简单的库存和销售应用程序,所以我在Android中编写了一个利润计算方法,用于计算所有产品的利润作为总利润,并在应用程序的TextView中显示出来。这些值都是双精度类型,所以我编写了下面的方法来计算总利润,但输出有些奇怪,它显示类似于“2.45116E7”或“1.22558E7”等内容,每次我运行应用程序时都会变化,但格式与总利润相同。所以我添加了Log.d来跟踪方法内部的输出,我意识到该方法确实从每个产品中获取利润值,并将它们累加为总利润,但是一旦总利润达到或超过10000000,它就会变成那个输出。请帮忙理解问题出在哪里,并提供可能的解决方案。下面是带有Log.d输出截图的方法。

private double getStoreProfits() {
    for (Product product : products) {
        Log.d("Profit", String.valueOf(product.getProfit()));
        totalProfit += product.getProfit();
        Log.d("Total Profits", String.valueOf(totalProfit));
    }
    return totalProfit;
}

输出截图如下:

有没有更好的方法来处理双精度数学计算?

英文:

I am building a simple inventory and sales app, so i wrote a profit calculation method in android to get the profits from all products as total profit and display it in TextView on the app. The values are in double so I wrote this method below to get the total profit but the output is a bit weird, it show's something like "2.45116E7" or "1.22558E7" and so on as it changes each time I run the app but has same format as the total profit. So I added Log.d to trace the outputs inside of the method and I realized that the method does get the profit values from each product and adds them up as the total profit but as soon as the total profit reaches 10,000,000 or above it changes to that output. Please I need help to understand what is wrong and possible solutions. See the method below with the screenshot of the Log.d outputs.

private double getStoreProfits() {
    for (Product product : products) {
        Log.d("Profit", String.valueOf(product.getProfit()));
        totalProfit += product.getProfit();
        Log.d("Total Profits", String.valueOf(totalProfit));
    }
    return totalProfit;
}

The output:

有没有更好的方法来处理双精度数学计算?

答案1

得分: 1

你可以将 String.valueOf(var) 替换为 String.format("%.2f", var)

这将会给你小数点前的所有数字,然后是小数点后两位。


当然,正如 Jon 所说,在这种情况下使用 BigDecimal 会更好一些。你可以将其转换为 float 或 double,并使用我已经描述过的方法(使用 floatValue()doubleValue()),或者你可以使用 toPlainString() 方法。

英文:

You can replace the String.valueOf(var) with String.format("%.2f", var).

This will give you all of the digits before the decimal point, followed by two digits after the decimal.


Of course, as Jon said, it would be a bit better in this case to use a BigDecimal. You can either convert it into a float or a double and use the method I already described (using floatValue() or doubleValue()) or you can use the toPlainString() method.

huangapple
  • 本文由 发表于 2020年7月27日 22:08:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63117100.html
匿名

发表评论

匿名网友

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

确定