BigDecimal 转换 Double(金额使用bigdecimal类型):摘自这里
double s=bigdecimal.doubleValue();
String 转换 BigDecimal:原作者传送门
BigDecimal bigDecimal=new BigDecimal(String);
String string = BingDecimal.toString();
设置小数位数,第一个变量是小数位数,第二个变量是取舍方法(四舍五入)
bigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
Object转BigDecimal类型:
public static BigDecimal getBigDecimal(Object value) { BigDecimal ret = null; if (value != null) { if (value instanceof BigDecimal) { ret = (BigDecimal) value; } else if (value instanceof String) { ret = new BigDecimal((String) value); } else if (value instanceof BigInteger) { ret = new BigDecimal((BigInteger) value); } else if (value instanceof Number) { ret = new BigDecimal(((Number) value).doubleValue()); } else { throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal."); } } return ret; }
Integer类的静态方法toString() Integer为null 空指针 原作者传送门
Integer a = 2; String str = Integer.toString(a
Integer类的成员方法toString()
Integer a = 2; String str = a.toString();
String类的静态方法valueOf()
Integer a = 2; String str = String.valueOf(a);
String.valueOf(Object obj)可以把整型(包括0)转化为字符串,但是Integer如果是null的话,会转化为”null”
public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); }
当Integer是null的情况下,我们也希望String是null
public static String toString(Object obj) { return (obj == null) ? null : obj.toString(); }
String转Integer (注意: String进行非空判断,否则很可能报空指针异常)
String str = "..."; Integer i = null; if(str!=null){ i = Integer.valueOf(str); }
保留6位小数点 原作者传送门
NumberFormat format = NumberFormat.getInstance(); format.setMinimumFractionDigits(6); String s= format.format(double/BigDecimal); DecimalFormat df = new DecimalFormat("0.000000"); String ss= df.format(double/BigDecimal);
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/226252.html原文链接:https://javaforall.net
