-1

This may be a repeat post, but I cannot find anything exactly to what I am looking for. I'm trying to take a simple double number, in any amount that won't exceed 100, and use string format to format it as XX.XX, such as a value like 45.4000000000

Things I have tried

string.format("%f",valuehere)
string.format("%2f",valuehere)

I don't quite understand the javadocs, but also I just want to ask as if I add a $ to %f like so $%f, valuehere, it should output it with the dollar sign as well right?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Not an answer, but as it seems like you're dealing with money, you should know that you shouldn't use `double` or `float` to represent money - use `BigDecimal` instead. See [here](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) for why. – DaveyDaveDave Feb 06 '21 at 23:19
  • thanks! i will look into this and try to figure out how to work out where i need the $ i can take it from here – Andrew Riley Feb 06 '21 at 23:26
  • Use a [currency format](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/text/NumberFormat.html#getCurrencyInstance()). For instance, `String s = NumberFormat.getCurrencyInstance().format(value);` – VGR Feb 07 '21 at 02:16

1 Answers1

2

You should add the decimal separator to your format. The format should be %.2f in your case as per the documentation.

What does it mean:

% is put at the start of the formatting

.2 Indicates that we want 2 digits after the decimal

f indicates that were dealing with a float here

String.format("%.2f",500.0545 )
Yoni
  • 1,370
  • 7
  • 17