简体   繁体   English

如何在Java中以.i递增字符串?

[英]How to increment a string by .i in Java?

My goal is to add value pairs to a HashMap and if a value is already taken it will increment the previous value by .i. 我的目标是将值对添加到HashMap ,如果已经使用了一个值,它将使前一个值增加.i。 What I mean by this is it would start as 0.1 ... 0.9 then 0.10 , 0.11 , 0.12 and so on... 我的意思是,它将开始为0.1 ... 0.9 ,然后0.100.110.12 ,等等...

I have started: 我已经开始了:

for (int i=0; i < 50; i++){
    Double test = Double.parseDouble( 0 + "." + i);

But I cannot find a suitable test to add a decimal place onto the double once it has reached .9 (0.9, 0.10) Everything that I've tried doesn't work reliably. 但是我找不到合适的测试来在双精度数达到.9(0.9,0.10)时在双精度数上加一个小数位。我尝试过的所有方法都无法可靠运行。 I was wondering if anyone could help. 我想知道是否有人可以提供帮助。

You can use DecimalFormat to get two decimal digits. 您可以使用DecimalFormat获取两个十进制数字。 The ".00" in the parameter tells the formatter to use two decimal places while the "#" means to display the whole number as it is 参数中的“ .00”告诉格式化程序使用两位小数,而“#”表示按原样显示整数

DecimalFormat df = new DecimalFormat("#.00");
    for(int i=0;i < 50 ;i++){
        Double test = Double.parseDouble( 0 + "." + i);
        System.out.println(df.format(test));

Output: 输出:

.00
.10
.20
.30
.40
.50
.60
.70
.80
.90
.10
.11
.12
.13
.14
.15
.16
.17
.18
.19
.20

What I mean by this is it would start as 0.1...0.9 then 0.10, 0.11,0.12 and so on... 我的意思是,它将从0.1 ... 0.9开始,然后是0.10、0.11,0.12,依此类推...

To print this pattern, there simplest solution is to print the value as it really a String operation rather than a mathematical one. 要打印此模式,最简单的解决方案是打印该值,因为它实际上是String运算而不是数学运算。

for (int i = 1; i <= 50; i++) 
    System.out.println("0." + i);

NOTE: For double the value 0.1 == 0.10 and there is no way to tell them apart. 注意:对于double 0.1 == 0.10值,值0.1 == 0.10 ,无法将它们区分开。

How about this 这个怎么样

double division = 1.0;
for(int i=0;i < 50 ;i++){
    if (i%10 == 0)
        division *= 10;

    Double test = i/division;
    System.out.print(test + " ");
}

It will have duplicate each time it goes down one decimal, but I hope for testing it should be ok. 每次下降一位小数时,它将具有重复项,但是我希望对其进行测试应该可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM