在小数点后面为什么两个零不在双精度中考虑。

huangapple go评论101阅读模式
英文:

after decimal why twoo zeros not consider in double

问题

  1. private static DecimalFormat df = new DecimalFormat("0.00");
  2. public static void main(String[] args) {
  3. double input = 300.00;
  4. System.out.println("double : " + input);
  5. Double d = Double.valueOf(df.format(input));
  6. System.out.println("##1::" + d);
  7. System.out.println("##2 ::" + df.format(input));
  8. System.out.println("##3 ::" + Double.valueOf(df.format(input)));
  9. }
  10. }

Output:

  1. double : 300.0
  2. ##1::300.0
  3. ##2 ::300.00
  4. ##3 ::300.0
英文:
  1. private static DecimalFormat df = new DecimalFormat("0.00");
  2. public static void main(String[] args) {
  3. double input = 300.00;
  4. System.out.println("double : " + input);
  5. Double d=Double.valueOf(df.format(input));
  6. System.out.println("##1::"+d);
  7. System.out.println("##2 ::"+df.format(input));
  8. System.out.println("##3 ::"+Double.valueOf(df.format(input)));
  9. }
  10. }

Output:

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

Expected output: 300.00

答案1

得分: 2

你可以使用BigDecimal来进行精度控制和四舍五入的操作。尝试以下代码:

  1. import java.math.BigDecimal;
  2. import java.math.RoundingMode;
  3. public class Test {
  4. public static void main(String[] args) {
  5. BigDecimal input = BigDecimal.valueOf(300);
  6. System.out.println("double 2 digit: " + Test.round(input, 2));
  7. System.out.println("double 5 digit: " + Test.round(input, 5));
  8. }
  9. public static BigDecimal round(BigDecimal bd, int scale) {
  10. return bd.setScale(scale, RoundingMode.HALF_UP);
  11. }
  12. }

输出如下:

  1. double 2 digit: 300.00
  2. double 5 digit: 300.00000
英文:

You can use BigDecimal for scale and round double. Try this :

  1. import java.math.BigDecimal;
  2. import java.math.RoundingMode;
  3. public class Test {
  4. public static void main(String[] args) {
  5. BigDecimal input = BigDecimal.valueOf(300);
  6. System.out.println("double 2 digit: " + Test.round(input, 2));
  7. System.out.println("double 5 digit: " + Test.round(input, 5));
  8. }
  9. public static BigDecimal round(BigDecimal bd, int scale) {
  10. return bd.setScale(scale, RoundingMode.HALF_UP);
  11. }
  12. }

Output like this :

  1. double 2 digit: 300.00
  2. double 5 digit: 300.00000

huangapple
  • 本文由 发表于 2020年5月30日 04:37:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/62094241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定