【问题标题】:Extracting digit values from before and after decimal points in Java从Java中的小数点前后提取数字值
【发布时间】:2020-11-06 21:53:04
【问题描述】:

我有 2 个值

字符串纬度 = "37.348541"; 字符串经度 = "-121.88627";

我想像下面这样提取值,而不对值进行四舍五入。

纬度 = "37.34"; 经度=“-121.88”;

我尝试使用 DecimalFormat.format,但它做了一些四舍五入,我想提取一个确切的值。

【问题讨论】:

    标签: java


    【解决方案1】:

    您可以使用String#substringString#indexOf 定义一个函数,如下所示:

    public class Main {
        public static void main(String[] args) {
            // Tests
            System.out.println(getNumberUptoTwoDecimalPlaces("37.348541"));
            System.out.println(getNumberUptoTwoDecimalPlaces("-121.88627"));
            System.out.println(getNumberUptoTwoDecimalPlaces("-121.8"));
            System.out.println(getNumberUptoTwoDecimalPlaces("-121.88"));
            System.out.println(getNumberUptoTwoDecimalPlaces("-121.889"));
        }
    
        static String getNumberUptoTwoDecimalPlaces(String number) {
            int indexOfPoint = number.indexOf('.');
            if (indexOfPoint != -1 && number.length() >= indexOfPoint + 3) {
                return number.substring(0, indexOfPoint + 3);
            } else {
                return number;
            }
        }
    }
    

    输出:

    37.34
    -121.88
    -121.8
    -121.88
    -121.88
    

    【讨论】:

      【解决方案2】:

      例如:

      String latitude  = "37.348541";
      int i = latitude.indexOf(".");
      if(i > 0 && i < latitude.length()-2) latitude  = latitude.substring(i, i+2);
      

      【讨论】:

        【解决方案3】:

        您可以使用BigDecimal 类和ROUND_DOWN 选项。所以代码可能是这样的:

        BigDecimal number = new BigDecimal("123.13298");
        BigDecimal roundedNumber = number.setScale(2, BigDecimal.ROUND_DOWN);
        System.out.println(roundedNumber);
        

        否则,您还可以使用本机 double 和 Math.floorMath.ceil 方法:

        double number = 123.13598;
        double roundedNumber = (number < 0 ? Math.ceil(number * 100) : Math.floor(number * 100)) / 100;
        System.out.println(roundedNumber);
        

        【讨论】:

        • 我认为他是专门寻找一个不四舍五入的数字,所以仅 BigDecimal 就足够了 :)
        猜你喜欢
        • 2017-06-25
        • 1970-01-01
        • 2019-07-12
        • 2017-08-31
        • 1970-01-01
        • 1970-01-01
        • 2014-08-24
        • 1970-01-01
        • 2011-08-05
        相关资源
        最近更新 更多