简体   繁体   English

DecimalFormat newFormat =新的DecimalFormat(“ ##。##”);

[英]DecimalFormat newFormat = new DecimalFormat(“##.##”);

DecimalFormat newFormat = new DecimalFormat("##.##"); giving me unexpected result for the below values: 给我以下值的意外结果:

for value 0.005 = 0.00
          0.015 = 0.02

DecimalFormat is not formatting the 0.005 to 0.01 . DecimalFormat不会将0.005 to 0.01格式化0.005 to 0.01 Please let me know how to get the value of 0.005 to 0.01 when DecimalFormat newFormat = new DecimalFormat("##.##"); 请让我知道当DecimalFormat newFormat = new DecimalFormat("##.##");时如何获得0.005 to 0.01的值DecimalFormat newFormat = new DecimalFormat("##.##"); is provided. 提供。

Thanks in Advance. 提前致谢。

After watching your comment, you can manually round to 2 digit and then do Decimal Format. 看完您的评论后,您可以手动舍入到两位数,然后执行十进制格式。

Here is the example: 这是示例:

public static void main(String[] args) {
    double input = 0.004;
    DecimalFormat formatter = getDecimalFormat(input); 
    System.out.println(formatter.format(round2Digit(input)));
    input = 0.005;
    formatter = getDecimalFormat(input); 
    System.out.println(formatter.format(round2Digit(input)));
    input = 0.015;
    formatter = getDecimalFormat(input); 
    System.out.println(formatter.format(round2Digit(input)));
}

private static DecimalFormat getDecimalFormat(double input){
    DecimalFormat formatter = (input % 1 == 0) ? new DecimalFormat("##.##"): new DecimalFormat("#0.00"); 
    return formatter;
}

private static double round2Digit(double input){
    double result = input * 100;
    result = Math.round(result);
    result = result / 100;
    return result;
}

Output: 输出:

0.00 0.00

0.01 0.01

0.02 0.02

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

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