BigDecimal金额的转换

支付金额一般使用BigDecimal类,涉及元转分,分转元的问题
代码如下:

import java.math.BigDecimal;

import com.taobao.util.Money;

/**
 * 金额转换工具类
 * 
 * @author wangxian
 * @since  2016-01-02
 */
public class MoneyUtils {

	/**
	 * 将分转换成元
	 * 
	 * @param cent
	 * @return
	 */
    public static BigDecimal convertToYuan(Long cent) {
        if (cent == null) {
            return null;
        }

        return new BigDecimal(cent).movePointLeft(2);
    }

	/**
	 * 由元转换成分
	 * 
	 * @param yuan
	 * @return
	 */
    public static long convertToCent(double yuan) {
        return new Money(yuan).getCent();
    }
    
    /**
	 * 由元转换成分
	 * 
	 * @param yuan
	 * @return
	 */
    public static long convertToCent(String yuan) {
        return new Money(yuan).getCent();
    }
    
    public static void main(String[] args) {
		System.out.println(convertToCent(18.5));
	}
}

若哪有不足,请大家多多指点!!

猜你喜欢

转载自blog.csdn.net/yijigu_JUN/article/details/89381144