简体   繁体   English

Java浮点值格式,保留两位小数

[英]Java Float value Formatting with two decimal places

Following are my codes to add two values 以下是我的代码以添加两个值

float ptoTotalAmount = 0;
Map<String, String> renewalDetailview = new LinkedHashMap<String, String>();
String Fee = driver
                .findElement(
                        By.xpath("//div[@data-bind='html: CURRenewalFees']"))
                .getText().substring(4).replace(",", "");       
        ptoTotalAmount += Float.valueOf((ptoFee));
        String surcharge = driver
                .findElement(By.xpath("//div[@data-bind='html: Surcharges']"))
                .getText().substring(4).replace(",", "");       
        ptoTotalAmount += Float.valueOf((surcharge));

        renewalDetailview.put("totalfee", Float.toString(ptoTotalAmount));

For an Example: 例如:

Fee - 31500.00,surcharge - 1500.00 费用-31500.00,附加费-1500.00

Fee + surcharge = 33000.00 费用+附加费= 33000.00

Thus, expected result for totalfee - 33000.00, but I'm getting 33000.0 因此,totalfee的预期结果-33000.00,但我得到33000.0

Therefore, I applied Formatting to my float value with 2 decimal places, but I'm not getting expected result. 因此,我将Formatting应用于我的float值(小数点后两位),但没有得到预期的结果。

DecimalFormat decimalFormat = new DecimalFormat();
        decimalFormat.setMinimumFractionDigits(2);

        renewalDetailview.put("totalfee", String.valueOf(df.format(ptoTotalAmount)));

I'm getting 330,00 something like this, please help me to format with 2 decimal places. 我得到330,00这样的东西,请帮助我格式化2位小数。

It looks like you are trying to model currency. 您似乎正在尝试对货币建模。 If so, you should check the answers on this post 如果是这样,您应该检查此帖子的答案

Try something like: 尝试类似:

float value = 33000.00f;//float??
String formattedString = String.format( "%.2f", value);
System.out.println(formattedString);
Output:
33000.00 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM