0

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. What I mean by this is it would start as 0.1 ... 0.9 then 0.10, 0.11, 0.12 and so on...

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. I was wondering if anyone could help.

5
  • 3
    floating point has NOT "reliable decimal digits" Commented Aug 6, 2018 at 16:27
  • 3
    floating point arithmetic is notoriously inaccurate due to the nature of computing decimals in binary. I would suggest scaling everything up x100 and storing your data as int Commented Aug 6, 2018 at 16:28
  • The problem with your logic is: what is i? 0.9 -> 0.10 suggests i = 0.1 but 0.10 -> 0.11 suggests i = 0.01. If your values actually are integers, i.e. 1 ... 9, 10, 11 etc., then please state so in your question - as well as why you prepend those with 0.. Commented Aug 6, 2018 at 16:29
  • If you want to count, you should use counting numbers: Integers. Counting with floating point numbers in a custom order is a bad idea. Commented Aug 6, 2018 at 16:30
  • Just use integers and a scaling factor, basically as you are doing now. What's wrong with your current approach? Commented Aug 6, 2018 at 17:46

3 Answers 3

1

What I mean by this is it would start as 0.1...0.9 then 0.10, 0.11,0.12 and so on...

To print this pattern, there simplest solution is to print the value as it really a String operation rather than a mathematical one.

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use DecimalFormat to get two decimal digits. The ".00" in the parameter tells the formatter to use two decimal places while the "#" means to display the whole number as it is

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 

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.