Formatting of data output

Asked

Viewed 357 times

0

So guys, I was "futucando" in java, but I came up with a question. How do I format a number that is in a method?

For example:

Code snippet:

JOptionPane.showMessageDialog(null,brand+ "Saldo atual de " +cliente1.getID()+" :"
+ "\n"+cliente1.getBalance());

This code prints in the format 0000.0 however I wanted to take this last decimal, already tried to use the %.4f and the %.4d, but it didn’t work out!

How do I get this one .0 of the exhibition?

Obs.: the method getBalance is a common method of a private double.

  • You want to simply remove the decimal or want to round as well?

  • Try this way: JOptionPane.showMessageDialog(null, String.format("Valor: %.0f", valor));

  • Diego, I just want to take, and Dener, it wasn’t, because when you put that comma he understands that is a parameter more, and not a concatenation

  • JOptionPane.showMessageDialog(null,brand+ "Saldo atual de " +cliente1.getID()+" :"
+ "\n"+((int)cliente1.getBalance()));

  • The comma to is indicates the second parameter of the format method, with it you can format the strings using these expressions, this is not a concatenation.

  • See if it works using the Decimalformat class: JOptionPane.showMessageDialog(null, "Valor: " + new DecimalFormat("####").format(valor));

  • For some reason the compiler takes his 4 zeros left and turns to 1 zero giving the output: 0

  • Please set exactly the exit rules. What happens if the decimals are not zero? You want to hide them always or only if they are zeros?

Show 3 more comments

1 answer

1

If you are working with four zeros left, you can use the following expression: %04.0f it indicates that the left side of the comma must be filled with four zeros and the right side must not contain numbers, that is to say no decimal part.

Take the example:

double valor = 0000.0;

JOptionPane.showMessageDialog(null, String.format("Valor: %04.0f", valor));

Exit:

Value: 0000

Source:https://stackoverflow.com/a/275715/5429980

Browser other questions tagged

You are not signed in. Login or sign up in order to post.