在Java中转换字符串2小数位

时间:2016-05-14 10:25:58

标签: java

在Java中,我试图解析一串格式" 0。##"浮动。该字符串应始终具有2个小数位。

public ArrayList getFixRateDetails (String merchantccy,String paymodetype,String amount) 

{
        String returnAmt ="";

ArrayList list= new ArrayList();

        float value=-1;
        try {
            NiCurrencyConverterProcessor nicc= new NiCurrencyConverterProcessor();
            list=nicc.getFixRateDetails(merchantccy,paymodetype);
            Float i = (Float.parseFloat((String) list.get(0)));
            Float j =  (Float.parseFloat(amount));


            value=i*j;
            list.set(0, value);
            list.add(2, i);
            GenericExceptionLog.log("PayPalUtility.java : In getFixRateDetails() : value:"+list,"paymenttarasectionsevlet111");
            DecimalFormat df = new DecimalFormat("0.00");
            String ReturnAmt = df.format(returnAmt);
            returnAmt=String.valueOf(value).trim();
            GenericExceptionLog.log("PayPalUtility.java : In getFixRateDetails() : value:"+returnAmt,"paymenttarasectionsevlet222");
        } catch (Throwable t) {
            GenericAsyncLogger.Logger(t,"ERROR","DB","Transaction","MIGSTxnUtility.java","postingAmtConversion()","NA","NA","","","paymenttarasectionsevlet");
            //GenericExceptionLog.exceptionJava(t,"postingAmtConversion()", "MIGSTxnUtility");
        }
            return list;
        }
}

1 个答案:

答案 0 :(得分:0)

您正在将格式化输出分配给不同的变量(ReturnAmt),并在日志中打印returnAmt。很明显,它会打印出没有格式化的值。

尝试

DecimalFormat formatter = new DecimalFormat("0.00");
returnAmt = formatter.format(value);

有关更多信息,请参阅DecimalFormat

示例:

public static void main(String...args){
        String returnAmt ="";
        Float i = 100f;
        Float j =  200f;
        Float value=i*j;
        DecimalFormat formatter = new DecimalFormat("0.00");
        returnAmt = formatter.format(value);
        System.out.println(returnAmt);
    }

输出:

  

20000.00