public class MoneyFormatUtil {
//分转换成元
public static String format_fen_as_yuan(int money_fen) {
float money_yuan = new BigDecimal(money_fen / 100f).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
return format(money_yuan);
}
/**
* @param @param money
* @param @return
* @return String
* @throws
* @Description: 格式化,保留小数点后两位
*/
public static String format(float money_yuan) {
String str = money_yuan + "";
int pos = str.indexOf(".");
if (pos < 0)
return str;
else {
String pre = str.substring(0, pos);
String last = str.substring(pos + 1);
try {
int xiaoshu = Integer.parseInt(last);
if (xiaoshu == 0) {
return pre;
}
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
}
DecimalFormat df = new DecimalFormat("##0.00");
return df.format(money_yuan);
}
}
//元转换为分 用法Money.fromYuan(yuan).fen();
public class Money implements Serializable, Parcelable {
BigDecimal value_bigDecimal;
int value_fen;
float value_yuan;
public Money(int value_fen) {
this.value_fen = value_fen;
value_bigDecimal = new BigDecimal(value_fen);
this.value_yuan = value_bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
}
public Money(Parcel in) {
this(in.readInt());
}
public static Money fromFen(String fen) {
return new Money(Integer.parseInt(fen));
}
public static Money fromFen(int fen) {
return new Money(fen);
}
public static Money fromYuan(String yuan_money_str) {
float money_shishou_yuan = Float.parseFloat(yuan_money_str);
return fromYuan(money_shishou_yuan);
}
public static Money fromYuan(float money_shishou_yuan) {
int fen = new BigDecimal(money_shishou_yuan).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).intValue();
Money money = new Money(fen);
return money;
}
public int fen() {
return value_fen;
}
public float yuan() {
return value_yuan;
}
public BigDecimal toBigDecimalValue() {
return value_bigDecimal;
}
/**
* 显示金额,比如: 3.1 (元,不包含单位)
*
* @return
*/
public String toStringAsYuan() {
return MoneyFormatUtil.format_fen_as_yuan(value_fen);
}
public Money multiply(BigDecimal num) {
return new Money(new BigDecimal(value_fen).multiply(num).intValue());
}
public Money divide(BigDecimal num) {
return new Money(new BigDecimal(value_fen).divide(num).intValue());
}
public Money add(BigDecimal num) {
return new Money(new BigDecimal(value_fen).add(num).intValue());
}
public Money subtract(BigDecimal num) {
return new Money(new BigDecimal(value_fen).subtract(num).intValue());
}
@Override
public String toString() {
return toStringAsYuan();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(value_fen);
}
public static final Parcelable.Creator<Money> CREATOR = new Parcelable.Creator<Money>() {
public Money createFromParcel(Parcel in) {
return new Money(in);
}
public Money[] newArray(int size) {
return new Money[size];
}
};
}