Java Separate方法将双输入转换为2位小数

时间:2015-01-17 15:32:31

标签: java

我在本论坛上阅读了很多关于将用户输入转换为2位小数的帖子。

但是,我需要自己编写一个方法,只负责将用户输入转换为2个小数位。

我目前遇到一个错误,即在进行十进制转换时无法将String转换为double。

以下是我目前的代码。

public class LabQuestion
{

static double twoDecimalPlace (double usrInput){
    DecimalFormat twoDpFormat = new DecimalFormat("#.##");
    usrInput=twoDpFormat.format(usrInput);
    return usrInput;
}

public static void main(String[] args) 
{  

    System.out.print("Enter a number on a line: ");        
    Scanner input = new Scanner(System.in);
    double d = input.nextDouble();

    twoDecimalPlace("Current input ",d);
}
}   

我怎样才能创建一个允许从用户转换为双输入的2位小数的方法?谢谢。

2 个答案:

答案 0 :(得分:2)

试试这个:

public Double formatDouble(Number number){
    return Double.parseDouble(String.format("%.3f", "" + number));  
}

答案 1 :(得分:1)

使用NumberFormat对象(如DecimalFormat对象)将String转换为数字,将其称为“解析”String或将数字称为String,这称为“格式化”数字,因此您需要决定你想用这种方法做什么。听起来你想要更改数字的显示以显示带有2个小数位的字符串表示,所以我认为你的输出应该是一个字符串。例如:


import java.text.DecimalFormat;
import java.util.Scanner;

public class NumberFormater {
   static DecimalFormat twoDpFormat = new DecimalFormat("#0.00");

   static String twoDecimalPlace(double usrInput) {
      String output = twoDpFormat.format(usrInput);
      return output;
   }

   public static void main(String[] args) {

      System.out.print("Enter a number on a line: ");
      Scanner input = new Scanner(System.in);
      double d = input.nextDouble();

      System.out.println("Output: " + twoDecimalPlace(d));
   }
}