---
title: "java常用方法"
author: "shuizhaosi888"
date: "2015-08-08T17:34:08Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2015-08-19T10:40:14Z"
id: 2233768
url: "https://flyouwith.iteye.com/blog/2233768"
---

---------------------------------------------保留2位小数------------------------------------------------

```
//---
new BigDecimal(3.333).setScale(2, RoundingMode.HALF_UP).floatValue();
//--
new DecimalFormat("##0.00").format(3.335);
//--
(float)Math.round(3.335*100)/100;
```

 

---------------------------------------------日期------------------------------------------------

```
		Date date = new Date();
		// 格式化日期
		SimpleDateFormat sf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
		String format = sf.format(date);
		// 日期运算
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		// 加天
		cal.add(Calendar.DATE, 100);
		Date time = cal.getTime();
```

 

---------------------------------------------随机数------------------------------------------------

```
	// method1
		Random ran = new Random();
		int nextInt = ran.nextInt(10);
		// method12
		int i = (int) (Math.random() * 10);
```

 

------------------------------------------正则表达式-------------------------------------------------

```
		Pattern patt  = Pattern.compile("[0-9]{4}\\-[0-9]{2}\\-[0-9]{2}");
		Matcher matcher = patt.matcher(d);
		while(matcher.find()){
			String group = matcher.group();
			System.out.println(group);
		}
```