JAVA求百分比__JAVA

來源:互聯網
上載者:User

import java.math.BigDecimal;

public class BIgDecimal {

 public static void main(String[] args) {

  double a = 2.0;
  double b = 5.0;
  double c = divide(a, b, 2);
  System.out.println(addZero(c) + "%");

  double d = divide(a, 1, 2);
  System.out.println(addZero(d) + "%");

 }

 public static double divide(double v1, double v2, int scale) {
  double c = div(v1, v2, scale + 2);
  // System.out.println(c+"%");
  return div(c * 100.0, 1, scale);
 }

 /**
  * 提供(相?)精?的除法?算。當?生除不盡的情況?,由scale參數指 定精度,以後的數字四捨五入。
  *
  * @param v1
  *            被除數
  * @param v2
  *            除數
  * @param scale
  *            表示表示需要精?到小數點以後幾位。
  * @return ?個參數的商
  */
 public static double div(double v1, double v2, int scale) {
  if (scale < 0) {
   throw new IllegalArgumentException(
     "The scale must be a positive integer or zero");
  }
  BigDecimal b1 = new BigDecimal(Double.toString(v1));
  BigDecimal b2 = new BigDecimal(Double.toString(v2));
  return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
 }

 /**
  * 提供精?的小數位四捨五入?理。
  *
  * @param v
  *            需要四捨五入的數字
  * @param scale
  *            小數點後保留幾位
  * @return 四捨五入後的?果
  */
 public static double round(double v, int scale) {
  if (scale < 0) {
   throw new IllegalArgumentException(
     "The scale must be a positive integer or zero");
  }
  BigDecimal b = new BigDecimal(Double.toString(v));
  BigDecimal one = new BigDecimal("1");
  return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
 }

 public static String addZero(double v) {
  StringBuffer s = null;
  String temp = String.valueOf(v);
  //String[] tempArray = temp.split(".");
  int point = temp.indexOf(".");
  int length = temp.length();
  int n = length - 1 - point;
  
  if (n > 0) {
   s = new StringBuffer(temp);
   for ( int i = 0; i < n; i++) {
    s.append(0);
   }
   return s.toString();
  } else {
   return temp;
  }

 }
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.