【问题标题】:after decimal why twoo zeros not consider in double小数点后为什么两个零不考虑双倍
【发布时间】:2020-05-29 20:37:07
【问题描述】:
private static DecimalFormat df = new DecimalFormat("0.00");

    public static void main(String[] args) {
        double input = 300.00;

        System.out.println("double : " + input);

        Double d=Double.valueOf(df.format(input));
       System.out.println("##1::"+d);
       System.out.println("##2 ::"+df.format(input));
       System.out.println("##3 ::"+Double.valueOf(df.format(input)));           
    }
}

输出:

double : 300.0 
##1::300.0 
##2 ::300.00 
##3 ::300.0 

预期输出:300.00

【问题讨论】:

  • //double : 300.0 //##1::300.0 //##2 ::300.00 //##3 ::300.0 //double vale 的预期输出为 300.00(不想要转换为字符串)
  • 什么意思?在第 2 种情况下,使用 DecimalFormat,您的值将打印为 300.00,就像您想要的那样。
  • 只是想将此 DecimalFormat 值分配给其他变量 Double b 这不可能吧? Double.valueOf(df.format(input)
  • 这有什么奇怪的?为什么您希望double 跟踪十进制零的数量?
  • @MayankL 一般人都明白 100.00 和 100.0 是一回事。如果您真的关心格式,则可以将 DecimalFormat 对象传递到显示号码的任何位置。更好的是,使用BigDecimal

标签: java math decimal


【解决方案1】:

您可以将 BigDecimal 用于刻度和双精度整数。试试这个:

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Test {

    public static void main(String[] args) {
        BigDecimal input = BigDecimal.valueOf(300);

        System.out.println("double 2 digit: " + Test.round(input, 2));
        System.out.println("double 5 digit: " + Test.round(input, 5));
    }

    public static BigDecimal round(BigDecimal bd, int scale) {
        return bd.setScale(scale, RoundingMode.HALF_UP);
    }
}

这样的输出:

double 2 digit: 300.00
double 5 digit: 300.00000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2017-04-26
    • 1970-01-01
    • 2013-04-19
    • 2018-12-24
    • 2018-05-14
    • 2014-01-05
    相关资源
    最近更新 更多