I have a problem in setting the precision of a non-output line.
This line of code writes the string on an applet.
g.drawString( "The numbers entered are: " + number1 +", "+number2 +", "+ number3, 25, 25 );
number1,number2 and number3 are three numbers of input. Now I want to see the output of the three numbers in 3 decimals. How can I write this line without changing the actual value of the numbers?
String.format gives you control over the format of interpolated values, like sprintf in C. It uses these format specifiers.
g.drawString(String.format("The numbers entered are: %.3f, %.3f, %.3f", number1, number2, number3), 25, 25)
Related
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.
I am performing some bit wise operations(& and |) on hexadecimal numbers.
Integer number1 = 0X00020000;
Integer number2 = 0X00000001;
System.out.println(number1);
System.out.println(number1 | number2);
System.out.println(number1 + number2);
Output :
131072
131073
131073
0X00020000 automatically got converted to 131072.
I am getting right answer but I am curious to know how & WHY Java converts hexadecimal number to decimal number.
I know how to convert hexadecimal number to decimal number.
0X00020000 will be converted to decimal as follows,
(2 X 16^4) + (0 X 16^3) + (0 X 16^2) + (0 X 16^1) + (0 X 16^0)
= (2 X 65536) + 0 + 0 + 0 + 0
= 131072
The right way to look at this is not as something being converted, but rather the way something is being displayed.
There is only one value stored for the variable, no matter how to write it in your source code. Write it anyway you like; once it is stored in memory, Java neither knows or cares what it looked like in your source code.
System.out.println renders the integer value, as a string, using decimal by default. Try System.out.printf("%x\n", number1); to see it rendered in hex.
Just keep in mind there is a big difference between the integer value and its string representation. If there is anything "converted" here, it's a conversion from an string (in your source) to an integer value (represented in memory) to a string (written to standard output). The last step uses decimal numerals by default.
I'm trying to print a double with only two decimals but the following code displays it as ##.##.#
double x, i = 3, j = 3, y;
x = Math.pow(i, j);
System.out.printf("two decimal places is: %.2f", x);
You should try DecimalFormat.Use the 0.00 pattern that specifies leading and trailing zeros, because the 0 character is used instead of the pound sign (#).
x = Math.pow(i, j);
//System.out.format("two decimal places is: %.2f", x);
DecimalFormat decimalFormat = new DecimalFormat("0.00");
System.out.println("two decimal places is: " + decimalFormat.format(x));
But as mentioned in comments section, try to post us the exact console output, it can help us figure out why your code it's not working.
I know this is a simple task, but I think I'm just having trouble with the formatting. I can get the GUI input box to ask for a number with 8 decimal places, but for the output box I can't figure out how to round the number the user input to 5 and 3 decimal places. This is what I'm stuck on:
import javax.swing.JOptionPane;
public class Ch3Assignment6 {
public static void main(String[] args) {
String Decimal_Eight = JOptionPane.showInputDialog ("Enter a decimal number with eight decimal places");
JOptionPane.showMessageDialog (null,
"The number you entered is: " + Decimal_Eight + "\n" +
"The number rounded to 5 decimal places is: " + String.format("%.5f", Decimal_Eight) + "\n" +
"The number rounded to 3 decimal places is: " + String.format("%.3f", Decimal_Eight));
}
}
It shows an error message/no output message box but i don't know how i'm entering the rounding part incorrectly. Thanks!
The String format you applied works on floating points, not on Strings. Try to parse it to a double first:
String input = JOptionPane.showInputDialog("Enter a decimal number with eight decimal places");
double Decimal_Eight = Double.parseDouble(input);
In addition to #MartijinCourteaux answer (+1), you can also use the NumberFormat class directly to make adjustments to how a number is formatted...
double value = 123.4567890123456789;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(5);
System.out.println(nf.format(value));
nf.setMaximumFractionDigits(3);
System.out.println(nf.format(value));
Which outputs...
123.45679
123.457
Now, obviously, I've started with a double, if you have String, you would only need to following #MartijnCourteaux answer to parse the value to a double...
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("##.##");