Insert $ in formatted float java

I am trying to format a float so that it has a dollar sign in front of it. I'm currently trying to get him to print 150 spots on the left.

System.out.printf("%150.2f", orderTotal);

This is what I use, but I cannot figure out where to put $ , I think I could do it all in String, but I was wondering if there is a way to do what I'm looking for?

+5
source share
4 answers

What about

 System.out.printf("%150s", String.format ("$%.2f", orderTotal)); 
+2
source
 System.out.printf("%150s$%.2f", "", orderTotal); 
+2
source

String.format is just the wrong tool for the task. Check the DecimalFormat.getCurrencyInstance what you want to use.

+2
source

I think this will give you what you want:

 System.out.printf("%150s", "$" + String.format("%.2f", orderTotal)); 

Using %150s , I think you're on the right track. To format your float so that it has two decimal places, but without adding extra spaces to the left, just leave the width field in the format specifier.

I assume that you want the entire field to have a width of 150; that is, if the currency part is "$101.20" , then you want to add 143 spaces to the left. If you really want 150 spaces, regardless of the amount, then the Reimeus answer will work.

Also, when using currencies, use BigDecimal instead of float or double . Floating-point types cannot handle decimal places exactly.

+1
source

Source: https://habr.com/ru/post/1208856/


All Articles