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...
Related
I have a user string generated by some computations. The user string is "3.2E7"
It is written in Scientific Notation. I need to convert it to standard notation because
the drawing instructions on the App overlap if it reads a Scientific Notation number.
I do know how to convert it to Standard Notation use the Number class, as the following shows:
String generated = "3.2E7"
try{
NumberFormat format = NumberFormat.getInstance();
Number my_number = format.parse(generated);
System.out.println("see my number: " + my_number); //this prints correctly: 32000000
}catch(Exception exception){
Log.d("see009",""+exception);
}
Now, the problem I am having is that if the variable 'generated' < 1 but greater than zero. Then, the NumberFormat class does not convert it properly:
String generated = "3.2E-7";
//inside the try catch block from above:
System.out.println("see my number: " + my_number); //this prints 3.2E-7 NOT: 0.00000032
Doesn't the Number class accept non-integers. How can I make the NumberFormat object format the Scientific notation number less than 1?
Working with the BigDecimal class I have been able to overcome the problem:
Simply do this:
String generated = "3.2E7";
BigDecimal big_decimal = new BigDecimal(generated);
System.out.println("look at this: " + big_decimal.toPlainString()); //will print: 32000000
generated = "3.2E-7";
big_decimal = new BigDecimal(generated);
System.out.println("look at this: " + big_decimal.toPlainString()); //will print: 0.00000032
BigDecimal even worked with powers in the magnitude of 20. It is a very efficient solution that is good for my needs.
I am still a bit new to programming and very new to Java, the kind of code I want is something like this:
double a = 10;
double b = 1234.123;
double c = 123.1234;
System.out.println(a);
System.out.println(b);
System.out.println(c);
And I want the output to read like:
10
1234.12
123.123
So basically, I want the numbers to be truncated to fit the number of spaces specified. In the above example, I wanted the numbers to fit into a field of 7 digits. I tried using printf() and NumberFormat, but neither of these seemed to work quite right, what other options do I have?.
Thanks for responding.
EDIT: #Pete, here is what I have been trying.
public static void main(String[] args) {
double num1 = 123.456789;
double num2 = 12.3456789;
double num3 = 1.23456789;
// create number format object
NumberFormat nf = NumberFormat.getInstance();
// limits number of fraction digits to five
nf.setMinimumFractionDigits(5);
System.out.println("Using NumberFormat:");
System.out.println();
System.out.println("num1 = " + nf.format(num1));
System.out.println("num2 = " + nf.format(num2));
System.out.println("num3 = " + nf.format(num3));
System.out.println("-------------------------------");
System.out.println("Using printf:");
System.out.println();
System.out.printf("%7f\n", num1);
System.out.printf("%7f\n", num2);
System.out.printf("%7f\n", num3);
}
The output for the above code is:
Using NumberFormat:
num1 = 123.45679
num2 = 12.34568
num3 = 1.23457
-------------------------------
Using printf:
123.456789
12.345679
1.234568
I am looking for a way to format any number to fit a field with a width of 7, and once the number of spaces is exceeded, it will begin to truncate from the end. I want a technique that will work regardless of which number is entered. both printf() and NumberFormat produce a specified number of decimal places, but neither cause my output to be truncated.
You can use DecimalFormat for the purpose. Define a DecimalFormat object in your class
private static DecimalFormat df2 = new DecimalFormat(".##");
While printing the values say stored in a variable called result, use below code to print the formatted value:
System.out.println(df2.format(result));
I have a situation where I need to preserve the number of decimal places for a number when formatting to a String using DecimalFormat, specifically for trailing zeros. I need to use DecimalFormat because I also need to avoid scientific notation for large numbers, and as seen here, this is the best way to do so. However, as you can see in that post, the code provided also removes trailing zeros, whereas I would like to preserve them.
1.00 -> "1.00"
1.000 -> "1.000"
I've seen a lot of questions that involve a fixed number of decimal places, but in my situation I need to account for a variable amount of decimal places. I looked into counting the number of decimal places, but since my input can also be a Double (in addition to BigDecimal), there appears to be no reliable way to count the digits after the decimal point for all numbers. Double.toString() does not work since Doubles break into exponential notation for very small and very big numbers. See here for more info regarding why it is difficult to count the number of decimal places in a double.
"Preserve" trailing zeros?
A double value doesn't know how many trailing zeroes you want to see. It is just a number, and 1.00 and 1.000 are the same number, i.e. the number 1. What you are asking cannot be done with a double value.
Now, BigDecimal does remember the number of trailing zeroes, so if you want to print a BigDecimal value, retaining the scale of the number, but ensuring it never prints in scientific notation, don't use a DecimalFormat, but instead use toPlainString():
Returns a string representation of this BigDecimal without an exponent field.
UPDATE
If you want to print a double value with as many decimal fraction digits as needed (i.e. no trailing zeroes), and want to make sure it never prints in scientific notation, use a DecimalFormat with very high MaximumIntegerDigits and very high setMaximumFractionDigits.
"Very high" means values exceeding the range of a double, so 999 is a good "round" number, though 330 would be high enough.
Test
DecimalFormat fmt = new DecimalFormat("0");
fmt.setMaximumIntegerDigits(330);
fmt.setMaximumFractionDigits(330);
System.out.println("0.0123400 = " + 0.0123400 + " = " + fmt.format(0.0123400));
System.out.println("123400.00 = " + 123400.00 + " = " + fmt.format(123400.00));
System.out.println("NaN = " + Double.NaN + " = " + fmt.format(Double.NaN));
System.out.println("-INFINITY = " + Double.NEGATIVE_INFINITY + " = " + fmt.format(Double.NEGATIVE_INFINITY));
System.out.println("+INFINITY = " + Double.POSITIVE_INFINITY + " = " + fmt.format(Double.POSITIVE_INFINITY));
System.out.println("MIN_NORMAL = " + Double.MIN_NORMAL + " = " + fmt.format(Double.MIN_NORMAL));
System.out.println("MIN_VALUE = " + Double.MIN_VALUE + " = " + fmt.format(Double.MIN_VALUE));
System.out.println("MAX_VALUE = " + Double.MAX_VALUE + " = " + fmt.format(Double.MAX_VALUE));
Output
0.0123400 = 0.01234 = 0.01234
123400.00 = 123400.0 = 123400
NaN = NaN = �
-INFINITY = -Infinity = -∞
+INFINITY = Infinity = ∞
MIN_NORMAL = 2.2250738585072014E-308 = 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022250738585072014
MIN_VALUE = 4.9E-324 = 0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000049
MAX_VALUE = 1.7976931348623157E308 = 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Either double (no precision, always approximating values), or BigDecimal.
Use BigDecimal as new BigDecimal("2.00") defining the correct scale (precision) of two digits. You can set the scale programmatically.
For database and calculation (like financial) BigDecimal is fine.
The scientific representation on output can be avoided in BigDecimal.toPlainString().
For double one could format with
s = String.format("%10.2f", 13.5789); // " 13.58"
All this is with a decimal point and no thousands separators.
Internationalized (localized) software will use a MessageFormat with a Locale (explicit or the default platform locale).
Locale.setDefault(new Locale("bg", "BG"));
s = MessageFormat.format("Number: {0, number, #.##}, "
+ "amount: {1, number, currency}",
42.125, 19.99);
I'm programming a simple java program. I need to get a string from input and divide it into two parts: 1-double 2-string.
Then I need to do a simple calculation on the double and send the result to the output with specific precision(4). It works fine, but there is a problem when the input is 0, then it doesn't work properly.
For example for these input, output will be:
1 kg
output:2.2046
3.1 kg
output:6.8343
But when the input is 0, the output should be 0.0000, but it shows 0.0 .
What should I do to force it to show 0.0000?
I read similar post about double precision, they suggest something like BigDecimal class, but I can't use them in this case,
my code for doing this is:
line=input.nextLine();
array=line.split(" ");
value=Double.parseDouble(array[0]);
type=array[1];
value =value*2.2046;
String s = String.format("%.4f", value);
value = Double.parseDouble(s);
System.out.print(value+" kg\n");
DecimalFormat will allow you to define how many digits you want to display. A '0' will force an output of digits even if the value is zero, whereas a '#' will omit zeros.
System.out.print(new DecimalFormat("#0.0000").format(value)+" kg\n"); should to the trick.
See the documentation
Note: if used frequently, for performance reasons you should instantiate the formatter only once and store the reference: final DecimalFormat df = new DecimalFormat("#0.0000");. Then use df.format(value).
add this instance of DecimalFormat to the top of your method:
DecimalFormat four = new DecimalFormat("#0.0000"); // will round and display the number to four decimal places. No more, no less.
// the four zeros after the decimal point above specify how many decimal places to be accurate to.
// the zero to the left of the decimal place above makes it so that numbers that start with "0." will display "0.____" vs just ".____" If you don't want the "0.", replace that 0 to the left of the decimal point with "#"
then, call the instance "four" and pass your double value when displaying:
double value = 0;
System.out.print(four.format(value) + " kg/n"); // displays 0.0000
System.out.format("%.4f kg\n", 0.0d) prints '0.0000 kg'
I suggest you to use the BigDecimal class for calculating with floating point values. You will be able to control the precision of the floating point arithmetic. But back to the topic :)
You could use the following:
static void test(String stringVal) {
final BigDecimal value = new BigDecimal(stringVal).multiply(new BigDecimal("2.2046"));
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(4);
df.setMinimumFractionDigits(4);
System.out.println(df.format(value) + " kg\n");
}
public static void main(String[] args) {
test("0");
test("1");
test("3.1");
}
will give you the following output:
0,0000 kg
2,2046 kg
6,8343 kg
String.format is just makign a String representation of the floating point value. If it doesnt provide a flag for a minimum precision, then just pad the end of the string with zeros.
Use DecimalFormat to format your double value to fixed precision string output.
DecimalFormat is a concrete subclass of NumberFormat that formats
decimal numbers. It has a variety of features designed to make it
possible to parse and format numbers in any locale, including support
for Western, Arabic, and Indic digits. It also supports different
kinds of numbers, including integers (123), fixed-point numbers
(123.4), scientific notation (1.23E4), percentages (12%), and currency
amounts ($123). All of these can be localized.
Example -
System.out.print(new DecimalFormat("##.##").format(value)+" kg\n");
I want to convert exponential to decimal. e.g. 1.234E3 to 1234.
It is not really a conversion, but about how you display the number. You can use NumberFormat to specify how the number should be displayed.
Check the difference:
double number = 100550000.75;
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(number);
System.out.println(formatter.format(number));
How about BigDecimal.valueOf(doubleToFormat).toPlainString()
While working with Doubles and Long numbers in Java you will see that most of the value are displayed in Exponential form.
For Example: In following we are multiplying 2.35 with 10000 and the result is printed.
//Division example
Double a = 2.85d / 10000;
System.out.println("1. " + a.doubleValue());
//Multiplication example
a = 2.85d * 100000000;
System.out.println("2. " + a.doubleValue());
Result:
2.85E-4
2.85E8
Thus you can see the result is printed in exponential format. Now you may want to display the result in pure decimal format like: 0.000285 or 285000000. You can do this simply by using class java.math.BigDecimal. In following example we are using BigDecimal.valueOf() to convert the Double value to BigDecimal and than .toPlainString() to convert it into plain decimal string.
import java.math.BigDecimal;
//..
//..
//Division example
Double a = 2.85d / 10000;
System.out.println("1. " + BigDecimal.valueOf(a).toPlainString());
//Multiplication example
a = 2.85d * 100000000;
System.out.println("2. " + BigDecimal.valueOf(a).toPlainString());
Result:
0.000285
285000000
The only disadvantage of the above method is that it generates long strings of number. You may want to restrict the value and round off the number to 5 or 6 decimal point. For this you can use java.text.DecimalFormat class. In following example we are rounding off the number to 4 decimal point and printing the output.
import java.text.DecimalFormat;
//..
//..
Double a = 2.85d / 10000;
DecimalFormat formatter = new DecimalFormat("0.0000");
System.out.println(formatter .format(a));
Result:
0.0003
I have just tried to compress this code with one line, it will print value of 'a' with two decimal places:
new DecimalFormat("0.00").format(BigDecimal.valueOf(a).toPlainString());
Happy Converting :)
you can turn it into a String using
DecimalFormat
the answer by #b.roth is correct only if it is country specific. I used that method and got i18n issue , because the new DecimalFormat("#0.00) takes the decimal seperator of the particular country. For ex if a country uses decimal seperation as "," , then the formatted value will be in 0,00 ( ex.. 1.2e2 will be 120.00 in some places and 120,00 ) in some places due to i18n issue as said here..
the method that i prefer is `(new BigDecimal("1.2e2").toPlainString() )
just add following tag to jspx:-
<f:convertNumber maxFractionDigits="4" minFractionDigits="2" groupingUsed="false"/>
String data = Long.toString((long) 3.42E8);
System.out.println("**************"+data);
try the following
long l;
double d; //It holds the double value.such as 1.234E3
l=Double.valueOf(time_d).longValue();
you get the decimal value in the variable l.
You can do:
BigDecimal
.valueOf(value)
.setScale(decimalLimit, RoundingMode.HALF_UP)
.toPlainString()