Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java分离方法将双输入转换为小数点后2位_Java - Fatal编程技术网

Java分离方法将双输入转换为小数点后2位

Java分离方法将双输入转换为小数点后2位,java,Java,我在这个论坛上读过很多关于将用户输入转换为小数点后2位的帖子 但是,我需要自己编写一个方法,并且只负责将用户输入转换为小数点后2位 我目前遇到一个错误,在进行十进制转换时无法将字符串转换为双精度 下面是我当前的代码 public class LabQuestion { static double twoDecimalPlace (double usrInput){ DecimalFormat twoDpFormat = new DecimalFormat("#.##"); us

我在这个论坛上读过很多关于将用户输入转换为小数点后2位的帖子

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

我目前遇到一个错误,在进行十进制转换时无法将字符串转换为双精度

下面是我当前的代码

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位?谢谢。

试试这个:

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

您可以使用NumberFormat对象(如DecimalFormat对象)将字符串转换为数字,这称为“解析”字符串或将数字转换为字符串,这称为“格式化”数字,因此您需要决定使用此方法执行哪种操作。听起来你想改变数字的显示,以显示一个小数点后两位的字符串,所以我认为你的输出应该是一个字符串。例如:



使用NumberFormat对象(如DecimalFormat对象)将字符串转换为数字,这称为“解析”字符串或将数字转换为字符串,这称为“格式化”数字,所以你需要决定你想用这个方法做什么。我想检查一下用户输入的public,以验证字符串输入是一个数字,还有一个单独的方法将验证过的输入(字符串输入被验证为数字输入)转换为小数点后2位。我可以知道我是否在正确的轨道上吗?在国家服务之后,我仍在追赶我的编程基础。感谢您提供的任何帮助,谢谢您的反馈。我试着实现它。它的工作是转换超过2个小数点的输入。但我希望用户即使是整数也能显示2个小数点,例如5.00。我可以知道,当用户没有输入整数时,我如何捕获?多谢各位much@RUiHAO:更改为新的十进制格式(“0.00”)谢谢。但是,我需要使用单独的方法来实现转换。这是一个额外的步骤,但这正是我所需要的,可悲的:(你很难在另一个函数中使用它吗?是的,必须使用一个新函数来执行转换。感谢你的帮助。谢谢!
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));
   }
}