- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class Demo1 {
- /**
- * @param args
- */
- public static void main(String[] args) {
- double num = 123.4567890123456;
- num = getNum(num, 2);
- System.out.println(num);
- }
- public static double getNum(double num, int i) {
- String numString = num + "";
- // 将正则表达式封装为Pattern对象
- String regex = "\\d+\\.\\d{" + i + "}";
- Pattern p = Pattern.compile(regex);
- // 获取匹配器
- Matcher m = p.matcher(numString);
- if (m.find()) {
- // 如果找到,获取这个数字
- String str = m.group();
- return Double.parseDouble(str);
- }
- throw new RuntimeException("获取的位数超过了小数的位数");
- }
- }
复制代码 刚写的,不知道符不符合你的要求.......
|