JAVA中各种单位之间的转换

本次讲述的是 JAVA中 各种单位之间的换算,其中包括货币单位的换算,时间单位的换算,以及小数点的保留和小数点与百分号之间的换算,都是从项目中抽取出来的,可能不太全面,把现有的先记录在这里,后面再继续补充。

(一)首先,这里是货币之间单位的换算:

/**
	 * 货币转换 1000000 return 1百万 10000 return 1万 1000 return 1千
	 * 
	 * @param amount
	 * @return
	 */
	public static HashMap<String, String> amountConversionMap(long amount) {
		HashMap<String, String> map = new HashMap<String, String>();

		if (amount >= 1000000) {
			map.put("amount", amount / 1000000 + "");
			map.put("amoun_unit", "百万");
			return map;
		}

		if (amount >= 10000) {
			map.put("amount", amount / 10000 + "");
			map.put("amoun_unit", "万元");
			return map;
		}

		if (amount >= 1000) {
			map.put("amount", amount / 1000 + "");
			map.put("amoun_unit", "千元");
			return map;
		}

		map.put("amount", amount + "");
		map.put("amoun_unit", "元");
		return map;
	}

	/**
	 * 1000000 return 1百万 10000 return 1万 1000 return 1千
	 * 
	 * @param amount
	 * @return
	 */
	public static String amountConversion(long amount) {
		if (amount >= 1000000) {
			return amount / 1000000 + "百万";
		}

		if (amount >= 10000) {
			return amount / 10000 + "万元";
		}

		if (amount >= 1000) {
			return amount / 1000 + "千元";
		}

		return amount + "元";
	}

	/**
	 * 10000 return 10,000
	 * 
	 * @param amount
	 * @return
	 */
	public static String amountConversionFormat(long amount) {
		return NumberFormat.getInstance().format(amount);
	}

	/**
	 * 10000 return 10,000
	 * 
	 * @param amount
	 * @return
	 */
	public static String amountConversionFormat(double amount) {
		return NumberFormat.getInstance().format(amount);
	}
	
都是一些常见的单位转换,还有国际标准的金额形式。

(二)然后是时间单位上的换算:

/**
	 * 1 Year 1年 1 Month 1个月 1 Day 1天
	 * 
	 * @param period
	 * @param periodUnit
	 * @return
	 */
	public static String periodConversion(int period, String periodUnit) {
		if ("Year".equals(periodUnit)) {
			return period + "年";
		}

		if ("Month".equals(periodUnit)) {
			return period + "个月";
		}

		if ("Day".equals(periodUnit)) {
			return period + "天";
		}

		return period + "";
	}

	/**
	 * 1 Year 1年 1 Month 1个月 1 Day 1天
	 * 
	 * @param period
	 * @param periodUnit
	 * @return
	 */
	public static String periodConversion(String periodUnit) {
		if ("Year".equals(periodUnit)) {
			return "年";
		}

		if ("Month".equals(periodUnit)) {
			return "个月";
		}

		if ("Day".equals(periodUnit)) {
			return "天";
		}

		return "";
	}
	
	
	/**
	 * ep: xx月xx日 xx:xx
	 * 
	 * get time ,only have month,date,hour and minutes
	 * @param time
	 * @return
	 */
	public static String getDateStringMonthDayTime(long time) {
		
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(time);
		StringBuilder builder = new StringBuilder();
		int month = cal.get(Calendar.MONTH)+1;
		builder.append(month);
		builder.append("月");
		builder.append(cal.get(Calendar.DATE));
		builder.append("日");
		builder.append("  ");
		builder.append(cal.get(Calendar.HOUR_OF_DAY));
		builder.append(":");
		builder.append(cal.get(Calendar.MINUTE));
		return builder.toString();
	}

	/**
	 * 123123123 2015-05-18 10:54:27
	 * 
	 * @param time
	 * @return
	 */
	public static String getDateString(long time) {
		SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		return myFmt.format(new Date(time));
	}

	public static String getDateStringMinute(long time) {
		SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		return myFmt.format(new Date(time));
	}

	/**
	 * ep: xx月xx日
	 * @param time longtime
	 * @return
	 */
	public static String getDateStringMonthAndDay(long time) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(time);
		StringBuilder sb = new StringBuilder();
		sb.append(cal.get(Calendar.MONTH)+1);
		sb.append("月");
		sb.append(cal.get(Calendar.DAY_OF_MONTH));
		sb.append("日");
		return sb.toString();
	}
	
	/**
	 * 123123123 2015-05-18
	 * 
	 * @param time
	 * @return
	 */
	public static String getDateStringDay(long time) {
		SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd");

		return myFmt.format(new Date(time));
	}

	public static boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
年月日,时分秒,基本也都齐了。

(三)最后一个是小数点的各种保留方式以及小数与百分数之间的转换

/*	*//**
	 * 9.658 return 9.65
	 */
	/*
	 * public static BigDecimal scale(double scale){ return new
	 * BigDecimal(scale).setScale(2, BigDecimal.ROUND_DOWN); }
	 *//**
	 * 9.658 return 9.65
	 */
	public static BigDecimal scale(BigDecimal scale) {
		return scale.setScale(2, BigDecimal.ROUND_DOWN);
	}

	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	
	/**
	 * string型保留两位小数
	 * @param value
	 * @return
	 */
	public static String CovertTwoDecimal(Object value) {
		DecimalFormat df = new DecimalFormat("######0.00");
		return df.format(Double.parseDouble((String) value));
	}
	
	/**
	 * double型保留两位小数
	 */
	public static String dobCoverTwoDecimal (double value) {
		DecimalFormat df = new DecimalFormat("######0.00");
		return df.format(value);
	}
	
	
	/**
	 * 小数转百分数
	 * 
	 */
	public static String changePointToPercent(Double point) {
        return String.valueOf(point*100);
    }
    
    	/**
	 * 0.00001 return 0.01%
	 * 
	 * @param percent
	 * @return
	 */
	public static String percentConversionFormat(double percent){
		NumberFormat percentNF = NumberFormat.getPercentInstance();
		percentNF.setMaximumFractionDigits(2);
		return percentNF.format(percent);
	}

(四)银行卡号中间数字的隐藏

    /**
     * 隐藏银行卡号中间部分数字
     */
    public static String hideBankCardNum(int lenth, String num) {
        return num.substring(0, 4) + "***********" + num.substring(lenth-4, lenth);
    }

(五)Map 与 Bean 格式之间的转换,以及 String,List 相关的转换

    /**
     * Map 转换为 Bean
     * @param map
     * @param object
     * @return
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     */
    public static Object mapToBean(Map map, Object object) throws IllegalAccessException, InvocationTargetException{
    	BeanUtils.populate(object, map);
    	return object;
    }

    /**
     * String转换Map
     *
     * @param mapText
     * :需要转换的字符串
     * :字符串中的分隔符每一个key与value中的分割
     * :字符串中每个元素的分割
     * @return Map<?,?>
     */
    public static Map<String, Object> StringToMap(String mapText) {

        if (mapText == null || mapText.equals("")) {
            return null;
        }
        mapText = mapText.substring(0);

        mapText = mapText;

        Map<String, Object> map = new HashMap<String, Object>();
        String[] text = mapText.split(","); // 转换为数组
        for (String str : text) {
            String[] keyText = str.split(","); // 转换key与value的数组
            if (keyText.length < 1) {
                continue;
            }
            String key = keyText[0]; // key
            String value = keyText[1]; // value
            if (value.charAt(0) == 'M') {
                Map<?, ?> map1 = StringToMap(value);
                map.put(key, map1);
            } else if (value.charAt(0) == 'L') {
                List<?> list = StringToList(value);
                map.put(key, list);
            } else {
                map.put(key, value);
            }
        }
        return map;
    }   

     /**
     * String转换List
     * @param listText
     * :需要转换的文本
     * @return List<?>
     */
    public static List<Object> StringToList(String listText) {
        if (listText == null || listText.equals("")) {
            return null;
        }
        listText = listText.substring(0);

        listText = listText;

        List<Object> list = new ArrayList<Object>();
        String[] text = listText.split(",");
        for (String str : text) {
            if (str.charAt(0) == 'M') {
                Map<?, ?> map = StringToMap(str);
                list.add(map);
            } else if (str.charAt(0) == 'L') {
                List<?> lists = StringToList(str);
                list.add(lists);
            } else {
                //由于服务器的图片前缀域名需要手动拼接,此处将每一张图片都拼接前缀域名
                list.add(AppApplication.imageUrlPrefix + "goods/" + str);
            }
        }
        return list;
    }

(六)这里再补充一点 Android 相关的工具,获取当前屏幕截屏和保存图片到系统指定的路径

    /**
     * 获取当前屏幕截屏
     * @param context 当前 Activity
     * @param bar 所截取部分顶部的位置(根据自身需求更改)
     * @param bottom 所截取部分底部的位置(根据自身需求更改)
     * 提示:截取顶部和底部不要的部分,剩下的就是需要截取的内容
     * @return
     */
    public static Bitmap getScreenShot(Activity context, View bar, LinearLayout bottom) {
        // 获取当前页面布局
        View view = context.getWindow().getDecorView().getRootView();
        // 设置缓存
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        // 从缓存中获取当前屏幕的图片
        Bitmap temp = view.getDrawingCache();

        // 获取状态栏高度
        Rect frame = new Rect();
        // 获取手机屏幕布局
        context.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        // 获取屏幕长和高
        int width = context.getWindowManager().getDefaultDisplay().getWidth();
        int height = context.getWindowManager().getDefaultDisplay().getHeight();
        // 获取系统状态栏高度
        int statusBarHeight_s = frame.top;
        // 获取项目状态栏高度
        int statusBarHeight_p = bar.getMeasuredHeight();
        //获取项目底部高度
        int statusBarHeight_b = bottom.getMeasuredHeight();
        // 去掉状态栏,如果需要的话
        Bitmap tempBmp = Bitmap.createBitmap(temp, 0, statusBarHeight_s + statusBarHeight_p,
                width, height - statusBarHeight_s - statusBarHeight_p - statusBarHeight_b);
        // 回收缓存
		/*if (!temp.isRecycled()) {
			temp.recycle();
		}*/
        return tempBmp;
    }

    /**
     * 保存图片到指定路径
     * @param context 当前所在 Activity
     * @param bmp Bitmap 对象
     */
    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "keen");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file)));
    }

注释都很清晰了,可能还不够完整,后面有新的还会再补充,要是发现有错误的地方欢迎指出,有新的建议欢迎留言!

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java,可以使用不同的方法来进行流量单位之间转换。 首先,要理解流量单位的基本概念,常见的单位有字节(Byte),千字节(Kilobyte),兆字节(Megabyte),吉字节(Gigabyte)等。 一种方法是使用Java的数值计算功能来实现单位转换。例如,假设有一个表示网络流量的整数变量byteCount,表示的是以字节为单位的流量大小。要将其转换为以兆字节为单位,可以使用以下代码: double megabyteCount = byteCount / (1024.0 * 1024.0); 这里,将字节数除以1024的平方来得到以兆字节为单位的值。 另一种方法是使用Java提供的单位转换工具类。例如,可以使用Java标准库java.util.concurrent.TimeUnit类来进行单位之间转换。以下是使用该类进行流量单位转换的示例代码: long byteCount = 1024 * 1024; // 表示1兆字节的流量 double kilobyteCount = TimeUnit.BYTES.toKilobytes(byteCount); double megabyteCount = TimeUnit.BYTES.toMegabytes(byteCount); double gigabyteCount = TimeUnit.BYTES.toGigabytes(byteCount); 这里,通过使用java.util.concurrent.TimeUnit类的静态方法toKilobytes、toMegabytes和toGigabytes,可以将以字节为单位的流量转换为以千字节、兆字节和吉字节为单位的值。 总结起来,我们可以使用数值计算或Java提供的单位转换工具类来实现Java流量单位转换。无论使用哪种方法,都可以方便地在Java程序进行流量单位转换的操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值