[java] DoubleUtil 数值转换工具类

package com.22pig.util;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import org.apache.commons.lang.StringUtils;

public class DoubleUtil {

/**
* NumberFormat is the abstract base class for all number formats.
* This class provides the interface for formatting and parsing numbers.
* @param d
* @return
*/
public static String formatDoubleUp(double d,int len) {
return String.format(“%.”+len+”f”, d);
}

public static String formatDoubleUp(String d,int len) {
if(d.contains(“.”)){
len = d.indexOf(“.”)+len;
if(len>d.length()) len = d.length();
d= d.substring(0,len);
}
return d;
}

/**
* NumberFormat is the abstract base class for all number formats.
* This class provides the interface for formatting and parsing numbers.
* @param d
* @return
*/
public static String formatDoubleDown(double d,int len) {
NumberFormat nf = new DecimalFormat(“#.#”);
nf.setMaximumFractionDigits(len); // 保留两位小数
nf.setRoundingMode(RoundingMode.DOWN);// 不需要四舍五入
return nf.format(d);
}

public static String addDouble(String[] doubleStrArr){
double sum =0;
for(int i=0;i<doubleStrArr.length;i++){
double tmp = parseDouble(doubleStrArr[i]);
sum+= tmp;
}
return String.valueOf(sum);
}

public static double parseDouble(String str){
if(StringUtils.isBlank(str) || “null”.equals(str.trim())){
str = “0”;
}
return Double.parseDouble(str);
}

//s为null或””时候返回0
public static String null2o(String s) {
return (s == null||s.equals(“”)) ? “0” : s;
}

public static double[] parseDouble(String[] dss){
double[] ds = new double[dss.length];
for(int i=0;i<dss.length;i++){
ds[i] = parseDouble(dss[i]);
}
return ds;
}
}

Leave a Comment