NumKit.java 1.5 KB
package tools;

import java.text.DecimalFormat;

import org.apache.commons.lang3.StringUtils;

/**
 * Depiction:
 * <p>
 * Modify:
 * <p>
 * Author: William Lynn
 * <p>
 * Create Date:2018年6月7日 下午6:25:16
 * 
 */
public class NumKit {

	public static int parseInt(String str) {
		int num = 0;
		try {
			num = Integer.parseInt(str);
		} catch (Exception e) {
		}
		return num;
	}

	public static float parseFloat(String str) {
		float num = 0;
		try {
			num = Float.parseFloat(str);
		} catch (Exception e) {
		}
		return num;
	}

	/**
	 * 截取字符串
	 * 
	 * @param source
	 *            原串
	 * @param number
	 *            前几位
	 * @return
	 */
	public static String subStr(String source, int number) {
		if (StringUtils.isBlank(source)) {
			return "";
		}

		int length = source.length();
		if (length >= number) {
			source = source.substring(0, number);
		}
		return source;
	}

	/**
	 * 格式化浮点数字
	 * 
	 * @param number
	 *            原始数据字符串
	 * @param count
	 *            小数点位数
	 * @return String
	 */
	public static String formatNumber(String number, int count) {
		count = count >= 0 ? count : 0;

		float tmp = 0.f;
		try {
			tmp = Float.parseFloat(number);
		} catch (Exception e) {
		}
		DecimalFormat format = new DecimalFormat("0");
		if (count > 0) {
			StringBuffer pattern = new StringBuffer();
			pattern.append("0.");
			for (int i = 0; i < count; i++) {
				pattern.append("0");
			}
			format = new DecimalFormat(pattern.toString());
		}

		return format.format(tmp);
	}
}