截取方法一 setScale方法
/***
* @Description: 數字截取後幾位,四舍五入
* @param: d
* @param: digit
*/
public static double round(double d, int digit) {
BigDecimal b = new BigDecimal(d);
return b.setScale(digit, BigDecimal.ROUND_HALF_UP).doubleValue();
}
截取方法二 利用java.text.DecimalFormat
/***
*
* @Description: 四舍五入
* @param d
* @param type 如: "#.00" 即表示為保留小數點後兩位 幾個0代表保留的位數
* @return
* @return double
* @throws @throws
*/
public static double subDecimalFormat(double d, String type) {
if (StringUtils.isBlank(type)) {
type = "#";
}
java.text.DecimalFormat df = new java.text.DecimalFormat(type);
double d1 = Double.parseDouble(df.format(d));
return d1;
}
将浮點數轉為百分數
/**
* @Description: 将浮點數轉為百分數
* @param d
* @param IntegerDigits 小數點前保留的位數
* @param FractionDigits 小數點後保留的位數
* @return String
* @time 2018年10月1日 上午11:09:35
*/
public static String getPercentFormat(double d,int IntegerDigits,int FractionDigits){
NumberFormat nf = java.text.NumberFormat.getPercentInstance();
nf.setMaximumIntegerDigits(IntegerDigits);//小數點前保留幾位
nf.setMinimumFractionDigits(FractionDigits);// 小數點後保留幾位
String str = nf.format(d);
return str;
}
将百分數轉為浮點數
/**
* @Description: 将百分數轉為浮點數
* @param d
* @return double
* @time 2018年10月1日 上午11:09:35
*/
public static double getPercentToDouble(String d, int digit){
NumberFormat nf=NumberFormat.getPercentInstance();
Number m = null;
try {
m = nf.parse(d);
} catch (ParseException e) {
e.printStackTrace();
}
return round(Double.parseDouble(String.valueOf(m.toString())), digit) ;
}
測試類:
import org.apache.commons.lang3.StringUtils;
import com.shihy.springboot.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ToFixedTest {
public static void main(String[] args) {
double d = 1.1234567879;
round(d, 0);
subDecimalFormat(d, "#.0000000");
doubleToPercent(d, Integer.MAX_VALUE, 1);
String str = "12.3%";
getPercentToDouble(str, 5);
}
public static void round(double d, int digit) {
double d1 = CommonUtils.round(d, digit);
log.info("四舍五入保留小數點後"+ digit + "位, 輸出結果為 :" + d1);
}
public static void subDecimalFormat(double d, String type) {
double d1 = CommonUtils.subDecimalFormat(d, type);
if (StringUtils.isBlank(type)) {
type = "#.0000000";
}
log.info("四舍五入保留小數點按照" + type +"格式, 輸出結果為 :" + d1);
}
public static void doubleToPercent(double d, int integerDigits, int fractionDigits) {
String percent = CommonUtils.getPercentFormat(d, integerDigits, fractionDigits);
log.info("浮點轉為百分數, 輸出結果為 :" + percent);
}
public static void getPercentToDouble(String d, int digit) {
double d1 = CommonUtils.getPercentToDouble(d, digit);
log.info("百分數轉為浮點,保留小數點後"+ digit +"位, 輸出結果為 :" + d1);
}
}
結果:
16:17:39.136 - 四舍五入保留小數點後0位, 輸出結果為 :1.0
16:17:39.145 - 四舍五入保留小數點按照#.0000000格式, 輸出結果為 :1.1234568
16:17:39.145 - 浮點轉為百分數, 輸出結果為 :112.3%
16:17:39.145 - 百分數轉為浮點,保留小數點後5位, 輸出結果為 :0.123