【问题标题】:Split the number on a decimal将数字拆分为小数
【发布时间】:2015-01-29 09:08:09
【问题描述】:

如何删除.后面的所有字符/数字在一个字符串中

String i = "154.232";

我只想要154

谢谢

我的代码:

distance = crntLocation.distanceTo(newLocation)/1000; // in km
double newKB = Math.floor(distance);
String product_distance = String.valueOf(newKB);    
product_distance.replaceAll("\\..*", "");

【问题讨论】:

  • 使用Math.floor 对值进行四舍五入。
  • 为什么不使用 int 而不是 double? newKB = (int) distance; 隐含地板功能。
  • @Mr T,如果你的 String 只包含数字,那么你不需要使用像 split() 这样的方法,你可以将它解析为 Double 并在结果上使用 Math.floor()价值。看看我的回答。

标签: java string split


【解决方案1】:
 public static void main(String[] args) {
        String str = "154.232";
        str = str.replaceAll("\\..*", "");
        System.out.println(str);
    }

str.substring(0, str.indexOf("."));

或 // 检查. 的索引是否不是-1,然后执行以下操作。

str.split(".")[0];

输出

154

【讨论】:

    【解决方案2】:
    i=i.split(".")[0];
    

    .split 函数将在点的任一侧返回一个字符串数组。 你想要 . 之前的部分,所以取数组中的第一个字符串。

    【讨论】:

      【解决方案3】:

      用途:

      Integer.parse()
      

      Integer.decode()
      

      【讨论】:

        【解决方案4】:

        用途:

        int id = str.indexOf(".");
        if (id >= 0) str = str.substring(0, id);
        

        杀死所有字符,包括第一个点,如果有的话。

        【讨论】:

          【解决方案5】:

          首先使用Double.parseDouble(String) 将其解析为Double 值,然后使用Math.floor 向下舍入,

          String yourString = "154.9418";
          // cast it to (int), since Math.floor returns a double
          int toInt = (int) Math.floor(Double.parseDouble(yourString));
          

          输出:

          154
          

          你可以使用StringTokenizer来分割字符串,

          String yourString = "154.964687";
          StringTokenizer st = new StringTokenizer(yourString,".");
          System.out.println(st.nextToken()); 
          

          输出:

          154
          

          【讨论】:

            猜你喜欢
            • 2011-10-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-04-27
            • 2012-12-22
            • 2015-04-04
            • 2014-12-17
            相关资源
            最近更新 更多