有 Java 编程相关的问题?

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

java添加一个十进制(.)在转换为int之前将其转换为字符串

我从java文本文件中读取了一个条形码。我把条形码分成几个部分,每个部分都有不同的含义。条形码的las 4位数字是价格,但当我读取它是一个字符串时,我必须将其转换为整数

// this is the bar code that is in the text file
// 10009999991020162590
File myFile = new File ("data.txt");
Scanner  inFile = new Scanner (myFile);

barCode = inFile.nextLine();
departmentStore = (Integer.parseInt(barCode.substring(0,4)));
partNumber = (Integer.parseInt(barCode.substring(4,10)));
date = (Integer.parseInt(barCode.substring(10,16)));
price = (Integer.parseInt(barCode.substring(16,20))); 

/*this is the price of the las 4 digits of the bar code as you can 
see is a string first but then i have to convert it into a int so i can do math but i want 
to put a dot(.) between the 25.90 then transform to int.

*/

共 (5) 个答案

  1. # 1 楼答案

    如果你要放置一个小数点,那么它就不会是int,你必须将它存储在floatdouble

    您可以使用简单的字符串连接来完成这个简单的任务

    double price = Double.parseDouble(barCode.substring(16,18) + "." + barCode.substring(18,20)); 
    
  2. # 2 楼答案

    答案实际上取决于解析后希望如何处理price变量

    以下是几个选项:

    1. 你可以把条形码的最后4位想象成以便士为单位的价格:

      int priceInPennies = Integer.parseInt(barCode.substring(16,20));
      
    2. 将价格保留为便士或将其转换为美元价格:

      double priceInDollars = Double.parseDouble(barCode.substring(16,20)) / 100;
      

      或者

      double priceInDollars = priceInPennies / 100.0;  
      
    3. 如果您只需要用于显示目的的价格,为什么不将价格保留为字符串

      String priceAsString = barCode.substring(16,18) + "." + barCode.substring(18,20);
      
  3. # 3 楼答案

    所以我建议首先把它解析成一个int值,然后生成十进制值。可以在字符串中放入一个十进制字符,但当您将其转换为int时,它将生成NumberFormatException,或者干脆放弃后面的十进制值

    因此,最好将其转换为int,然后将值除以100或100.0,以获得所需的输出

  4. # 4 楼答案

    选项1(坏):

    float price = (Float.parseFloat(
                   barCode.substring(16,18) + "." + barCode.substring(18,20))); 
    

    我不完全确定地点。java会独立于语言环境设置进行解析吗?例如,在德国,正确的十进制值被写为25,90,而不是25.90。因此,我建议您使用更通用的方法,而不是硬编码的.

    选项2(更好,imho):

    float price = Float.parseFloat(String.format("%02.2f", 
                 (float)(Integer.parseInt(barCode.substring(16,20))) / 100.0f));
    
  5. # 5 楼答案

    注意,正如我们在评论中讨论的那样,不可能在整数变量中存储浮点数。似乎你想把这个数字存储在一个双精度存储器中,通过输入一个。(点)在两位数之间。这不是一项艰巨的任务,只需注意代码即可

    .
    .
    .
    .
    String price=barCode.substring(16,20);
    //get first two part of string add a . and then the last two char
    price=price.substring(0,2)+"."+price.substring(2,4);
    //then convert it to double
    double p=Double.parseDouble(price);
    

    还有一个简单的方法。 .

    int price = (Integer.parseInt(barCode.substring(16,20))); 
    double p=price/100.0;