java将流量KB转换为GB、MB、KB格式

        /**
	 * 转换流量格式为xxGBxxMBxxKB
	 * @param flow 156165(xxxxxx)
	 */
	public String changeFlowFormat(String flow) {
		Integer flows = Integer.valueOf(flow);
		if (flows > 0 && flows < 1024) {//小于1M
			return flows + "KB";
		} else if (flows >= 1024 && flows < 1048576) {//大于1M小于1G
			int changeM = (int) Math.floor(flows / 1024);//整M数
			int surplusM = (int) Math.floor(flows % 1024);//除M后的余数
			if (surplusM > 0) {//余数大于0KB
				return changeM + "MB" + surplusM + "KB";
			} else {//整M,没有余数
				return changeM + "MB";
			}
		} else if (flows >= 1048576) {//大于1G
			int changeG = (int) Math.floor(flows / 1048576);//整G数
			int surplusG = (int) Math.floor(flows % 1048576);//除G后的余数
			if (surplusG >= 1024) {//余数大于大于1M
				int changeM = (int) Math.floor(surplusG / 1024);
				int surplusM = (int) Math.floor(surplusG % 1024);
				if (surplusM > 0) {//余数大于0KB
					return changeG + "GB" + changeM + "MB" + surplusM + "KB";
				} else {//整M,没有余数
					return changeG + "GB" + changeM + "MB";
				}
			} else if (surplusG < 1024 && surplusG > 0) {//余数小于1M,大于0K
				int surplusM = (int) Math.floor(surplusG % 1024);
				return changeG + "GB" + surplusM + "KB";
			} else {
				return changeG + "GB";
			}
		}
		return "暂无数据";
	}

     //js方法

    /**
     * 转换流量格式为xxGBxxMBxxKB
     * @param flow 156165(xxxxxx)
     */
    function changeFlowFormat(flow) {
        console.log(flow);
        if (flow >= 0 && flow < 1024) {//小于1M
            return flow + "KB";
        } else if (flow >= 1024 && flow < 1048576) {//大于1M小于1G
            var changeM = Math.floor(flow / 1024);//整M数
            var surplusM = Math.floor(flow % 1024);//除M后的余数
            if (surplusM > 0) {//余数大于0KB
                return changeM + "MB" + surplusM + "KB";
            } else {//整M,没有余数
                return changeM + "MB";
            }
        } else if (flow >= 1048576) {//大于1G
            var changeG = Math.floor(flow / 1048576);//整G数
            var surplusG = Math.floor(flow % 1048576)//除G后的余数
            if (surplusG >= 1024) {//余数大于大于1M
                var changeM = Math.floor(surplusG / 1024);
                var surplusM = Math.floor(surplusG % 1024);
                if (surplusM > 0) {//余数大于0KB
                    return changeG + "GB" + changeM + "MB" + surplusM + "KB";
                } else {//整M,没有余数
                    return changeG + "GB" + changeM + "MB";
                }
            } else if (surplusG < 1024 && surplusG > 0) {//余数小于1M,大于0K
                var surplusM = Math.floor(surplusG % 1024);
                return changeG + "GB" + surplusM + "KB";
            } else {
                return changeG + "GB";
            }
        }
        return "暂无数据";
    }
posted @ 2021-08-09 17:30  初出茅庐小菜鸡  阅读(1265)  评论(0编辑  收藏  举报