1

Is there a way to dynamically format a float value?

I thought i could do something like this:

System.out.println(new BigDecimal(String.format("%" + k + "s", answer)).toPlainString());

Where k is the increments each time through a loop... however, this doesn't seem to do the trick...

i want the numbers to appear like this:

0.7897
0.78977
0.789778
0.7897789 

any ideas?

9
  • is k supposed to be the precision? What kind of format are you tryign to do? Also, why are you creating a BigDecimal based on a String? I'm really confused about what you are trying to do here. Commented Sep 11, 2013 at 20:55
  • @crush yes k is the precision Commented Sep 11, 2013 at 20:58
  • 3
    Hehe. Do you need the actual float value, or just string printing? You could hack it and use substring. Commented Sep 11, 2013 at 20:59
  • let's say k is 4 and you're input is 0.789, should it print out "0.7890"? Commented Sep 11, 2013 at 20:59
  • also, I noticed that you don't seem to round... is this what you want? Commented Sep 11, 2013 at 21:00

4 Answers 4

7
for (int i=3; i<10; i++) {
    System.out.println(String.format("%1." + i + "f", Math.PI));
}

Something like that should work

[tmp] % java Foo
3.142
3.1416
3.14159
3.141593
3.1415927
3.14159265
3.141592654
Sign up to request clarification or add additional context in comments.

2 Comments

this would work but the example in the question doesn't round.
Wanted to mention "%."+i+"f" but I thought I was thinking in C++. Very good answer.
2

Using a NumberFormat can be done like this example

 float f = 0.342566246
 NumberFormat n = NumberFormat.getInstance()
 for(int i = 2; i< 6;i++)
 {
     n.setMaximumFractionDigits(i)
     System.out.println(n.format(f))
 }

Gives, which rounds.

0.34
0.343
0.3426
0.34257

You can control rounding by adding a RoundingMode eg adding

n.setRoundingMode(RoundingMode.DOWN);

Gives

0.34
0.342
0.3425
0.34256

Comments

0

Have a look at: http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

I can't help you any further since I don't know the format you're interested in.

1 Comment

Hey, @CommuSoft, you should try to summarize the contents of your link instead of having just a link in answers in case of linkrot. meta.stackexchange.com/questions/8231/…
0

If you don't need the actual float value of your variables, you can just print them out in the loop using the subString API from String.

The advantage is that your formatted variable won't be rounded. This is a hack-ish alternative to the other two answers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.