【Java 自定义工具类】百分比计算工具类以及计算相关的问题(138)

16 篇文章 0 订阅

详解:
1.列举了4种百分比转化方式;
2.解决百分比计算加和不为100%的问题;
3.百分比计算保留小数点后一位或者两位或者N位;
4.double类型数字相加减的时候结果与预期不符合;
5.不同入参方式计算(数组和单个值);

详解4:举例说明
eg:131+121=251.00000000000000001(且大概率难以重现,有时候有这种情况,有时候又不会发生)
原因:在数值相加减时,会先被转化成机器数然后再运算,即二进制的形式。但是在转换成二进制代码表示的时候,存储小数部分的位数会有不够的现象,即无限循环小数,这就是造成微小差距的主要原因。

工具类代码:

package com.day02;

import java.text.DecimalFormat;

/*
 * 百分比计算工具类
 * 
 */

public class PercentageUtil {
	public static void main(String[] args) {
		
		// 测试方式一
		System.out.println("测试方式一:"+calculationMethod_1(14,30));	
		System.out.println("----------------");
		// 测试方式二
		System.out.println("测试方式二:"+calculationMethod_2(123.446));
		System.out.println("----------------");
		// 测试方式三
		double[] nums = {33.0, 35.0, 18.0, 12.0,21.0}; // 要计算的数
		String[] result = calculationMethod_3(nums);	
		for (int i = 0; i < result.length; i++) {
			System.out.println("测试方式三:"+result[i]);
		}
		System.out.println("----------------");
		// 测试方式四
		String d = calculationMethod_4(50,1000);
		System.out.println("测试方式四:"+d);
		
	}
	
	/*
	 * 计算方式一:
	 * 
	 */
	public static String calculationMethod_1(double value,double total) {
		double percentage = (value / total) * 100;  // 格式化百分比
		// 创建DecimalFormat对象,指定保留一位小数,如果想保留两位,改成new DecimalFormat("0.00")
		DecimalFormat decimalFormat = new DecimalFormat("0.0");  
		String Percentage = decimalFormat.format(percentage) + "%";  // 格式化百分比
		return Percentage;
	}
	
	/*
	 * 计算方式二:
	 * 
	 */
	public static String calculationMethod_2(double number) {
		double roundedNumber = (double) Math.round(number);
        DecimalFormat df = new DecimalFormat("#.##");  // 保留两位("#.##");保留一位("#.#");
        //DecimalFormat 的 setDecimalSeparatorAlwaysShown() 方法默认是 true,即小数点后的零将始终显示出来。要避免输出后缀 0,设置该属性为 false
        df.setDecimalSeparatorAlwaysShown(false);
        String formattedNumber = df.format(number);
		return formattedNumber;
	}
	
	/*
	 * 计算方式三:各自所占比例相加为100%;
	 * 
	 */
	public static String[] calculationMethod_3(double nums[]) {
		String[] result = new String[nums.length];
		double total = 0.0; // 总数
		// 计算总数
		for (double num : nums) {
		   total += num;
		}
		// 计算各自所占比例和相应的百分比
		for (int i = 0; i < nums.length; i++) {
		    double ratio = (nums[i] / total) * 100;
		    // 创建DecimalFormat对象,指定保留一位小数(保留两位:0.00)
		    DecimalFormat decimalFormat = new DecimalFormat("0.0");  
			String Percentage = decimalFormat.format(ratio);  // 格式化百分比
			// 最后一位数据采用减法,这样总和为100%;
			if(i == nums.length - 1) {
				Double temp = 0.0;
				for (int j = 0; j < result.length-1; j++) {
					temp += Double.valueOf(result[j]);
				}
				double value = 100 - temp;
				// 格式化百分比:解决double类型数字相加减的时候结果与预期不符合
				String Percentage2 = decimalFormat.format(value);
				result[i] = String.valueOf(Percentage2);
			}
			else {
				result[i] = Percentage;
			}
		}
		for (int i = 0; i < result.length; i++) {
			result[i] = result[i] + "%";
		}
		return result;
	}
	
	/*
	 * 计算方式四:
	 * 备注:保留小数点后一位或者两位调整:new DecimalFormat("##.00%"); // ##.00%
	 * 
	 */
	public static String calculationMethod_4(long a, long b) {
        String result = "";
        double y = a * 1.0;
        double z = b * 1.0;
        if (y == 0 || z == 0) {
            return "0.00%";  // 小数点后保留两位;
        }
        double res = y / z;
        DecimalFormat dec = new DecimalFormat("##.00%"); // ##.00%   小数点后保留两位;

        result = dec.format(res);
        // ##.00% 使用这种转换方式,整数位如果是0 则会被删除  即0.35% 会出现 .35%的情况
        char c = result.charAt(0);
        if (String.valueOf(c).equals(".")) {
            StringBuffer sb = new StringBuffer();
            sb.append("0").append(result);
            return String.valueOf(sb);
        }
        return result;
    }
	
}

测试输出:

测试方式一:46.7%
----------------
测试方式二:123.45
----------------
测试方式三:27.7%
测试方式三:29.4%
测试方式三:15.1%
测试方式三:10.1%
测试方式三:17.7%
----------------
测试方式四:5.00%

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KevinDuc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值