英文:
after decimal why twoo zeros not consider in double
问题
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)));
}
}
Output:
double : 300.0
##1::300.0
##2 ::300.00
##3 ::300.0
英文:
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)));
}
}
Output:
double : 300.0
##1::300.0
##2 ::300.00
##3 ::300.0
Expected output: 300.00
答案1
得分: 2
你可以使用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
英文:
You can use BigDecimal for scale and round double. Try this :
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);
}
}
Output like this :
double 2 digit: 300.00
double 5 digit: 300.00000
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论