com.webapp.utils.format.FmtUtils Maven / Gradle / Ivy
package com.webapp.utils.format;
import java.beans.Beans;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import org.apache.commons.lang3.math.NumberUtils;
import com.webapp.utils.string.Utils.Symbol;
public final class FmtUtils {
private String data;
private boolean endZero = true;
private static final ThreadLocal local = new ThreadLocal();
private FmtUtils(String data){
this.data = data;
}
/** setData **/
private FmtUtils setData(String data, boolean endZero) {
this.data = data;
this.endZero = endZero;
return this;
}
/** local data **/
private static FmtUtils localData(String result) {
if (local.get() == null) local.set(new FmtUtils(result));
return local.get().setData(result, true);
}
// pattern()
public static FmtUtils of(T data) {
String result;
if(Beans.isInstanceOf(data, Number.class)){
result = data.toString();
}else if(Beans.isInstanceOf(data, String.class)){
result = String.valueOf(data).replaceAll("(? 0){
format.setMaximumFractionDigits(scale);
format.setMinimumFractionDigits(scale);
}
return format.format(parse);
}
private String getPattern(String data) {
return getPattern(data, "", "");
}
private String getPattern(String data, String before) {
return getPattern(data, before, "");
}
private String getPattern(String data, String before, String after) {
int length = data.replaceFirst("\\d+\\.|\\d+", "").length();
String symbol = endZero ? "0" : "#";
StringBuffer pattern = new StringBuffer(before + "0");
pattern.append(length > 0 ? "." : Symbol.Empty);
for(int i=0; i