当前位置:   article > 正文

double类型的加减乘除_double加减乘除

double加减乘除

import java.math.BigDecimal;

由于Java的简单类型不能够精确的对浮点数进行运算,这个工具类提供精 确的浮点数运算,包括加减乘除和四舍五入。 

加:doubleValue() 减:substract() 乘:multiply() 除:divide()

  1. import java.math.BigDecimal;
  2. /**
  3. * 由于Java的简单类型不能够精确的对浮点数进行运算,这个工具类提供精 确的浮点数运算,包括加减乘除和四舍五入。
  4. */
  5. public class DoubleUtils{
  6. private static final int DEF_DIV_SCALE = 2;
  7. /**
  8. * @Description 两个Double数相加
  9. *
  10. * @param d1
  11. * @param d2
  12. * @return Double
  13. */
  14. public static Double add(Double d1,Double d2){
  15. BigDecimal b1 = new BigDecimal(d1.toString());
  16. BigDecimal b2 = new BigDecimal(d2.toString());
  17. return b1.add(b2).doubleValue();
  18. }
  19. /**
  20. * @Description 两个Double数相减
  21. *
  22. * @param d1
  23. * @param d2
  24. * @return Double
  25. */
  26. public static Double sub(Double d1,Double d2){
  27. BigDecimal b1 = new BigDecimal(d1.toString());
  28. BigDecimal b2 = new BigDecimal(d2.toString());
  29. return b1.subtract(b2).doubleValue();
  30. }
  31. /**
  32. * @Description 两个Double数相乘
  33. *
  34. * @param d1
  35. * @param d2
  36. * @return Double
  37. */
  38. public static Double mul(Double d1,Double d2){
  39. BigDecimal b1 = new BigDecimal(d1.toString());
  40. BigDecimal b2 = new BigDecimal(d2.toString());
  41. return b1.multiply(b2).doubleValue();
  42. }
  43. /**
  44. * @Description 两个Double数相除
  45. *
  46. * @param d1
  47. * @param d2
  48. * @return Double
  49. */
  50. public static Double div(Double d1,Double d2){
  51. BigDecimal b1 = new BigDecimal(d1.toString());
  52. BigDecimal b2 = new BigDecimal(d2.toString());
  53. return b1.divide(b2,DEF_DIV_SCALE,BigDecimal.ROUND_HALF_UP).doubleValue();
  54. }
  55. /**
  56. * @Description 两个Double数相除,并保留scale位小数
  57. *
  58. * @param d1
  59. * @param d2
  60. * @param scale
  61. * @return Double
  62. */
  63. public static Double div(Double d1,Double d2,int scale){
  64. if(scale<0){
  65. throw new IllegalArgumentException(
  66. "The scale must be a positive integer or zero");
  67. }
  68. BigDecimal b1 = new BigDecimal(d1.toString());
  69. BigDecimal b2 = new BigDecimal(d2.toString());
  70. return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
  71. }
  72. /**
  73. * @Description String类型小数与Double类型的转换
  74. */
  75. public static void StrToDouble(){
  76. String str="1234.5678";
  77. double num;
  78. DecimalFormat myformat = new DecimalFormat("#0.00");
  79. num = Double.parseDouble(str);//直接转换为double类型
  80. num = Double.parseDouble(myformat.format(num));//保留2为小数
  81. System.out.println(num);
  82. }
  83. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/319842?site
推荐阅读
相关标签
  

闽ICP备14008679号