jiangping
2024-12-02 2b72be7962e44d251fdecc8fdc6465ed7237536e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.doumee.core.utils;
 
import java.util.regex.Pattern;
 
/**
 * Java正则校验密码至少包含:字母数字特殊符号中的2种
 */
import java.math.BigDecimal;
import java.util.regex.Pattern;
 
    public class ScientificNotationTUtil {
        private static final Pattern SCIENTIFIC_NOTATION_PATTERN =
                Pattern.compile("[+-]?\\d*(\\.\\d+)?[eE][+-]?\\d+");
 
        public static boolean isScientificNotation(String value) {
            return SCIENTIFIC_NOTATION_PATTERN.matcher(value).matches();
        }
 
        public static double convertScientificNotationToDouble(String scientificNotation) {
            if (isScientificNotation(scientificNotation)) {
                return (Double.parseDouble(scientificNotation));
            } else {
                throw new IllegalArgumentException("The string is not in scientific notation.");
            }
        }
        public static String convertToString(String numberStr) {
            try {
                // 尝试直接将字符串转换为BigDecimal
                return new BigDecimal(numberStr)+"";
            } catch (NumberFormatException e) {
                // 如果转换失败,则尝试解析科学计数法
                String[] parts = numberStr.split("E");
                if (parts.length == 2) {
                    // 这是科学计数法,需要转换
                    BigDecimal number = new BigDecimal(parts[0]);
                    int exponent = Integer.parseInt(parts[1]);
                    return number.scaleByPowerOfTen(exponent)+"";
                }
            }
            return  numberStr;
        }
 
        public static BigDecimal convertScientificNotationToBigDecimal(String scientificNotation) {
            if (isScientificNotation(scientificNotation)) {
                return new BigDecimal(scientificNotation);
            } else {
                throw new IllegalArgumentException("The string is not in scientific notation.");
            }
        }
 
        public static void main(String[] args) {
//            String scientificNotation = "1.23e+3";
//            String scientificNotation = "1.5345690888E10";
            String scientificNotation = "15345690888";
            System.out.println("Is scientific notation: " + isScientificNotation(scientificNotation));
            System.out.println("Converted to String: " + convertToString(scientificNotation));
//            System.out.println("Converted to BigDecimal: " + convertScientificNotationToBigDecimal(scientificNotation));
        }
    }