required output:
Code: 123 Title: BookA Fees(SGD): $20.00
Loan Duration: 3 wks
return String.format("%-20s%-20s%\n", "Code: " + code, "Title: " + title, "%.2f\nFees(SGD): $" + fees, "Lesson Duration: " + lessonDuration + "wks");
it only returns only the first 3 (code, title, fees) but not loan duration. also where do i put in %.2f for fees so that it will always be of 2 decimal place?
Your question asks about "Loan Duration", but your example code uses "Lesson Duration". That could be your problem.
That %.2f should work for setting two decimal places. How is it behaving?
When you use String.format, you usually just pass your variables in and use the correct percent signs for your variables' types. For instance, if you want to format an integer, you use %d: String.format("Here is an integer: %d", myInt). For strings, you use %s, and for doubles, you use %f (with .2 to indicate the number of decimal places as you've already found out. You put all of your formatting in the first string parameter. All you have to do then is this:
String code = "123";
String title = "BookA";
double fees = 20.943;
int lessonDuration = 3;
String str = String.format("Code: %s\nTitle: %s\nFees(SGD): $%.2f\nLesson Duration: %d wks",
code,
title,
fees,
lessonDuration);
You should go read this article here so you understand formatting in Java and don't fail your test.
Related
I'll start right off the bat by saying that this was a homework project (that was submitted weeks ago). I got decent marks, but I would like to know if I could have done it better.
We had to output an Employee's name, age, salary and bonus in this format:
Name Age Salary Bonus
Xxxxxx xx $ xxxxx.xx $ xxxx.xx
We aren't allowed to use loops and only have to output one employee.
Now this is how I did the output:
String employeeSalary = String.format("%.2f", myEmployee.getSalary());
String employeeBonus = String.format("%.2f", myEmployee.calculateBonus());
System.out.printf("\f%-10s %-10s %-12s %-10s\n", "Name", "Age", "Salary", "Bonus");
System.out.printf("%-10s %-10s %-12s %-10s", myEmployee.getName(), myEmployee.getAge(), "$ " + employeeSalary, "$ " + employeeBonus);
Thank you,
Mike :)
Your example shows you are already aware of format method in String class. So you could have used it to format entire output instead of using both format and printf methods.
System.out.println(String.format("%-10s %-10s $ %-12.2f $ %-10.2f",
myEmployee.getName(), myEmployee.getAge(),
myEmployee.getSalary(), myEmployee.calculateBonus()));
I want to format a double value into a style of having
Currency Format Symbol
Value rounded into 2 decimal places
Final Value with thousand separator
Specifically using the java.util.Formatter class
Example :-
double amount = 5896324555.59235328;
String finalAmount = "";
// Some coding
System.out.println("Amount is - " + finalAmount);
Should be like :-
Amount is - $ 5,896,324,555.60
I searched, but I couldn't understand the Oracle documentations or other tutorials a lot, and I found this link which is very close to my requirement but it's not in Java -
How to format double value into string with 2 decimal places after dot and with separators of thousands?
If you need to use the java.util.Formatter, this will work:
double amount = 5896324555.59235328;
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("$ %(,.2f", amount);
System.out.println("Amount is - " + sb);
Expanded on the sample code from the Formatter page.
You could use printf and a format specification like
double amount = 5896324555.59235328;
System.out.printf("Amount is - $%,.2f", amount);
Output is
Amount is - $5,896,324,555.59
To round up to 60 cents, you'd need 59.5 cents (or more).
Instead of using java.util.Formatter, I would strongly suggest using java.text.NumberFormat, which comes with a built-in currency formatter:
double amount = 5896324555.59235328;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String finalAmount = formatter.format(amount);
System.out.println("Amount is - " + finalAmount);
// prints: Amount is - $5,896,324,555.59
Example:
System.out.println("the investment doubled after "+year+" years.");
Can someone please explain why the int variable year is inside quotations and pluses?
Adding some spacing around the operators may make this statement clearer:
System.out.println("the investment doubled after " + year + " years.");
This statement prints the result of a concatination of three strings, achieved by the two + operators:
"the investment doubled after "
The implicit conversion of the int variable year to a string
" years."
It is like this. And + is used for String concatenation. In this year is converted into String from int implicitly.
"the investment doubled after " + year + " years."
^-------inside quotes-------^ ^-----^Inside quotes
Your variable year is not inside quotes, it's actually outside of quotes. It is in between of + sign because you are concatenating it.
Here you are using the public void println(String x); method. Which means the integer will concatenated to the string when you append the years to the string, that is the reason we are using the + operator.
I want to convert Float into String, but I've got a problem with precision
I want to see something like 5.50 in String format.
If I use
String price = new DecimalFormat("#.##").format(ClientOrder.TOTAL_PRICE);
totalPriceTV.setText("" + price + " " + OptionsApp.CURRENCY);
I will get price looking like an integer, or like 5.5
ClientOrder.TOTAL_PRICE is a float number
So how to get String with 2 numbers after point?
You can write something like this too:
String price = String.format("%.2f", ClientOrder.TOTAL_PRICE);
The right pattern is "#.00".
String price = new DecimalFormat("#.00").format(ClientOrder.TOTAL_PRICE);
totalPriceTV.setText("" + price + " " + OptionsApp.CURRENCY);
You can use String.substring(int, int) with String.indexOf(String).
String totalPrice = "5.50158941";
String price = totalPrice.substring(0, totalPrice.indexOf(".") + 3);
I'm pretty new to Java programming and couldn't find an answer to my problem anywhere. Basically, I have successfully created a program that builds a chart of Celsius to Fahrenheit conversions and Fahrenheit to Celsius conversions, however my looped print statements are not lined up correctly after the number 9 similar this:
9.0 48.2 40.0 4.44
10.0 50.0 41.0 5.0
I was required to use two separate methods to calculate the conversions and then call them within the main method. Here is the main method with the println statement that I am reffering to:
public static void main(String[]args){
double celsius = 1;
double fahrenheit = 32;
while(celsius <= 50 && fahrenheit <= 120){
double toFarhenheit = celsiusToFahrenheit(celsius);
double toCelsius = fahrenheitToCelsius(fahrenheit);
DecimalFormat fardec = new DecimalFormat("#.##");
toFarhenheit = Double.valueOf(fardec.format(toFarhenheit));
DecimalFormat celsdec = new DecimalFormat("#.##");
toCelsius = Double.valueOf(celsdec.format(toCelsius));
System.out.println(celsius + " " + toFarhenheit + " " + fahrenheit +
" " +toCelsius);
celsius++;
fahrenheit++;
}
}
To make a long story short, is there anyway to use a printf with this kind of long print statement so that the numbers will line up with one another?
In the past I have used printf %3d and %5d and the like to line integers up, however, I couldn't get this to work at all with this particular print statement.
Any ideas and/or help would be much appreciated.
Use System.out.printf(...) and a format String to output your data in regular columns. Avoid using \t as it is unreliable. For example please look here.
Eventually your code would look like:
System.out.printf(formatString, celsius, toFarhenheit, fahrenheit, toCelsius);
Where the formatString is a String that uses printf format specifiers and width constants that would allow for pretty output. I'll let you experiment with format Strings. It would also end with "%n" so that it becomes in effect a println with formatting.
Adding to what Hovercraft Full Of Eels said, using System.out.printf without "\t" is a better solution.
For example, you should be able to do something like this:
String myformat = "%0$10s";
Explanation of the format:
%0s identifies your output as a string
$10 tells it to ensure that a minimum of 10 characters are written to the output. Hence, you'll have a fixed width.
See http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax for some more details
[haven't used java in a while so someone do correct me if I'm off]
Use \t to format them as this spaces them out evenly.
System.out.println(celsius + "\t" + toFarhenheit + "\t" + fahrenheit +
"\t" +toCelsius);
Using "\t" or using printf is probably not going to help you out as what ever space is being added takes into consideration the 2 string literals. For Eg. 9.0 is 3 chars long and 10.0 is 4 chars long.. so in this case spaces applied are correct but your string literals itself are of different length.
Try changing the code like below, use one more hash.
DecimalFormat fardec = new DecimalFormat("##.##");