有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果字符串是实十进制数字,则在Java中仅显示十进制数字

有时一个双精度数字可以有一个整数值,有时它可以是一个“真正的十进制数字”

我正在寻找一种方法,如果没有整数值,则只打印十进制数字:

public static void main(String[] args) {

    double test = 1; // should print "1"
    double test2 = 1.5; // should print "1,5"

    System.out.println(String.format("%.1f", test));  // OUTPUT: "1,0"
    System.out.println(String.format("%.1f", test2)); // OUTPUT: "1,5"
}

谢谢你们的帮助,伙计们

问候


共 (4) 个答案

  1. # 1 楼答案

    //obtain an array of strings based on the comma as delimeter
    String[] array = java.util.Arrays.toString(String.valueOf(test).split("\\,"));
    
    //if the second string (the decimal part) is not 0, then print both strings with a comma in between, othwersise only the integer part
    if(array[1].equals("0")==false)
        System.out.println(array[0]+","+array[1]);
    else
        System.out.println(array[0]);
    
  2. # 2 楼答案

    您可以尝试以下方法:

        public static boolean isInteger(double num){
    
           if (num % 1 == 0){
               return true;
           } else {
               return false;
           }
    
        }
    

    它检查数字是否包含十进制值。 如果该方法返回true,则可以将其转换为long或int

  3. # 3 楼答案

    对于十进制数,您可以指定后面的数字数量

    public static void printNumber(double num){
    
           if (num % 1 == 0){
               System.out.println(String.format("%.0f", num));
           } else {
               System.out.println(String.format("%.1f", num));
           }
    
        }
    
    public static void main(String[] args) {
    
        double test = 1; // should print "1"
        double test2 = 1.5; // should print "1,5"
    
        printNumber(test);  // print 1
        printNumber(test2); // print 1,5
    
    }
    
  4. # 4 楼答案

    通过正则表达式

     double test2 =1.5;
    
        if(!Double.toString(test2).matches("\\d+\\.0+")){ // matchs test2 whether it contains 0s after .(decimal) or not
                    System.out.println(test2); //1.5
    System.out.println(Double.toString(test2).replaceAll("\\.", ","));// 1,5
                }