I'm trying to get my output to print to only 1 decimal place.I've tried using the DecimalFormat but it is messing up the alignment of my output.
Here is what my output was before I used the DecimalFormat:
ID Programs Midterm Final Weighted Average
-- -------- ------- ----- -------- -------
1212 90.0 85.0 92.0 89.30000000000001 Pass
6666 60.0 80.0 90.0 78.0 Pass
7777 90.0 90.0 90.0 90.0 Pass
8888 95.0 87.0 93.0 91.8 Pass
9999 75.0 77.0 73.0 74.8 Pass
And here is what it looks like after I used the DecimalFormat:
ID Programs Midterm Final Weighted Average Programs grade
-- -------- ------- ----- ---------------- --------------
1212 90.0 85.0 92.0 89.3 Pass
6666 60.0 80.0 90.0 78 Pass
7777 90.0 90.0 90.0 90 Pass
8888 95.0 87.0 93.0 91.8 Pass
9999 75.0 77.0 73.0 74.8 Pass
Here is the code I am working with:
DecimalFormat df = new DecimalFormat("#.#");
double Program = inputFile.nextDouble(); //Programs
double Midterm = inputFile.nextDouble(); //Midterm
double Final = inputFile.nextDouble(); //Final
double WAverage = (Program * WProgram) + (Midterm * WMidterm)+
(Final * WFinal);
classAve = classAve +WAverage;
NumStudents++;
String ResultsString = new String(" Fail");
if (WAverage >= 70)
ResultsString = " Pass";
System.out.println(ID +" " + Program +" "+ Midterm +" "+ Final +
" "+ df.format(WAverage) +" " +ResultsString );
Use
String.format("%.1f", WAverage);
Instead of
df.format()
No need for DecimalFormat
You have to set the minimum amount of decimals:
df.setMinimumFractionDigits(1);
You can accomplish what you want by changing one character: Use .0 instead of .# in your format string if you want to always display one decimal place, even if that digit is zero. Here's the documentation: http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
Then the first line of your code snippet would be:
DecimalFormat df = new DecimalFormat("#.0");
Related
Anyone Can help me to fix my Java Function to use it in my Routine.
The Function will remove exponent and put it in a Float format.
This is the function :
float amount = 3.53435E12;
java.text.DecimalFormat df = new java.text.DecimalFormat("# .# ");
String s=df.format(amount );
System.out.println("amount = " + s);
it will convert the number format from this 3.53435E12 to this 3 534 350 000 000
the result will be like this ---> 3 534 350 000 000
Now i want to create a function in my Routine in order to use it in Tmap with my column.
Thanks.
In your routine named for Example MyRoutine
public static double convertNumber(double message) {
java.text.DecimalFormat df = new java.text.DecimalFormat("# .# ");
String s=df.format(message );
System.out.println("amount = " + s);
return (Double.parseDouble(s)) ;
}
The in tMap simply call
MyRoutine.convertNumber(row1.amount)
This question already has answers here:
Show padding zeros using DecimalFormat
(8 answers)
Closed 7 years ago.
I created this code to display a certain output however the output is displayed with as so:
First Class Parcel - Cost is £3.3
John Smith, 1 Downing Street, SQ13 9DD
Weight = 1.342kg.
This piece of code is the part of the output about(First Class Parcel - Cost is £3.3) However instead of displaying 3.3 I want to display 3.30.
#Override
public String toString() {
String str = "";
double cost = 0.00;
if (this.isFirstClass()){
cost = 3.30;
str = "First Class Parcel";
} else {
cost = 2.80;
str = "Second Class Parcel";
}
return str + " - Cost is £" + cost + "\n" + super.toString() + "\n";
}
This will help you :
DecimalFormat df = new DecimalFormat("#.00");
double d= 23.2;
System.out.println(df.format(d));
Use DecimalFormat. Something on the lines like following
double cost = 3.30;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("Cost is £" + df.format(cost) );
Have you tried:
String.format( "%.2f", cost);
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)
I'm trying to have only three numbers after the comma in my double value. I do:
DecimalFormat dfi_ = new DecimalFormat("#.000");
My double :
double myD = 6.082483660549182E-15;
System.out.println("DF Version of myD: " + dfi_.format(myD));
but the result was : DF Version of myD: ,000
Thanks,
The result is correct. It displays the (localized) number, with a precision of 3 digits after the decimal.
The value 6.082483660549182E-15 is 0.0000000000000060824.., which is very close to 0.
Now, to display the number in Scientific Notation, consider a format of "###.0E0" - this should result in an output of 6,082E-15 (where the decimal is determined by locale), which I believe is desired.
(If the question is just about the comma, then that's merely a localization issue.)
Try this one. Find out your region (Locale) and use that locale specific DecimalFormat.
For more info have a look at NumberFormat#getNumberInstance(Locale).
double no = 123456.7890;
for (Locale locale : Locale.getAvailableLocales()) {
NumberFormat numberFormat = DecimalFormat.getNumberInstance(locale);
System.out.println("========================================");
System.out.println(locale.getDisplayCountry() + " - " + locale.toString());
System.out.println(numberFormat.format(no));
DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(locale);
String numberPattern = decimalFormat.toLocalizedPattern();
System.out.println(numberPattern);
}
output:
========================================
Malaysia - ms_MY
123,456.789
#,##0.###
========================================
Qatar - ar_QA
123,456.789
#,##0.###;#,##0.###-
========================================
Iceland - is_IS
123.456,789
#.##0,###
========================================
Finland - fi_FI
123 456,789
# ##0,###
========================================
- pl
123 456,789
# ##0,###
========================================
Malta - en_MT
123,456.789
#,##0.###
and so on...
I'm extracting data from a file in this format:
`1111 1.0 2222 53.5 3333 0.3 4444 541.1 5555 0.3'
Now suppose I want to replace 0.3 with 32.2. How do I best go about it in Java?
I thought of using str.replaceAll(str.substring(beginIndex, endIndex), replacement). However, it requires a beginning and end Index, which I can't easily provide.
What's the best method in Java?
EDIT: there may be multiple instances of 0.3. I only wish to change the one that occurs after a certain no. of spaces. This one occurs after 5 spaces, for example.
The following in concise and dynamically adaptable. I instantiated variables to provide an example, but the crucial parts are the first and last lines of the code:
String regex = "(?<=\\s{%s})%s(?=\\s{%s})";
String numSpaces = "1";
String number = "0.3";
String replacement = "32.2";
String yourString = "1111 1.0 2222 53.5 3333 0.3 4444 541.1";
yourString = yourString.replaceAll(String.format(regex, numSpaces, number, numSpaces),
replacement);
System.out.println(yourString);
//prints 1111 1.0 2222 53.5 3333 32.2 4444 541.1
In this example, "(?<=\\s{%s})%s(?=\\s{%s})" would become: (?<=\\s{1})0.3(?=\\s{1}) which means "0.3" with one whitespace tokens before and after, it takes advantage of positive look behinds and aheads so that only the number is replaced and the spaces are left the same.
Also, note that replaceAll() should only be used when dealing with regular expressions. If you're not using regular expressions, use .replace() instead. .replace() replaces all instances, too, the name is slightly misleading.
Note, if the number of spaces before and after are supposed to be different, just change the final argument to String.format() to be whatever number of spaces should be after the number.
EDIT:Apparently we're defining spaces differently. I assumed that a certain number of spaces literally means a certain number of spaces before and after the number in question.
Try,
String str="1111 1.0 2222 53.5 3333 0.3 4444 541.1 ";
str=str.replaceAll(" 0.3 ", " 32.2 ");
System.out.println(str);
Assuming you want to replace ALL of the 0.3s in your String (tested and works):
String s = "1111 1.0 2222 53.5 3333 0.3 4444 541.1";
// replace "0.3 " at the beginning of the String
if (s.substring(0,4).equals("0.3 "))
s = "32.2" + s.substring(3);
// replace " 0.3" at the end of the String
if (s.substring(s.length() - 4).equals(" 0.3"))
s = s.substring(0, s.length() - 4) + " 32.2";
// replace all the rest of the "0.3" in the String
s = s.replaceAll(" 0.3 ", " 32.2 ");
Input/Output:
Input:
"1111 1.0 2222 53.5 3333 0.3 4444 541.1"
Output:
"1111 1.0 2222 53.5 3333 32.2 4444 541.1"
Input:
"0.3 1111 1.0 2222 53.5 3333 0.3 4444 541.1 0.3"
Output:
"32.2 1111 1.0 2222 53.5 3333 32.2 4444 541.1 32.2"
Input:
"0.35 1111 1.0 2222 53.5 3333 0.3 4444 540.3"
Output:
"0.35 1111 1.0 2222 53.5 3333 32.2 4444 540.3"
Try using this regular expression, \b0\.3\b.
\b is a word boundary, which allows you to treat 0.3 as word.
0 is 0
\. represents a dot literal. You have to escape the dot because a dot in regular expressions will match any character.
3 is a literal 3.
Remember in java you have to escape the backslash, so your final regular expression is this.
String regexp = "\\b0\\.3\\b";
Example Junit Test
package demo;
import static org.junit.Assert.*;
import org.junit.Test;
public class Matchy {
String regexp = "\\b0\\.3\\b";
#Test
public void test() {
String str = "0.3 0.2 123.4 0.3 0.3 013";
String result = str.replaceAll(this.regexp, "32.2");
String expect = "32.2 0.2 123.4 32.2 32.2 013";
assertEquals(str, expect, result);
}
#Test
public void test2() {
String str = "1111 1.0 2222 53.5 3333 0.3 4444 541.1";
String result = str.replaceAll(this.regexp, "32.2");
String expect = "1111 1.0 2222 53.5 3333 32.2 4444 541.1";
assertEquals(str, expect, result);
}
}
I think this code should do what you want.
String str = "1111 1.0 2222 53.5 3333 0.3 4444 541.1 5555 0.3";
int numSpaces = 5;
String replacement = "32.2";
Matcher m = Pattern.compile("((?:\\S+\\s+){" + numSpaces + "})(\\S+)(.*)").matcher(str);
m.find();
System.out.println("replaced " + m.group(2) + " with " + replacement + " at index " + m.start(2));
System.out.println(m.group(1) + replacement + m.group(3));
I have to get my output to line up beneath a heading. No matter what I do, I cannot get to line up. The item name is very long also, and the words end up wrapping to the next line when I open my outfile. Here is my current output:
8 items are currently available for purchase in Joan's Hardware Store.
----------Joan's Hardware Store-----------
itemID itemName pOrdered pInStore pSold manufPrice sellPrice
1111 Dish Washer 20 20 0 250.50 550.50
2222 Micro Wave 75 75 0 150.00 400.00
3333 Cooking Range 50 50 0 450.00 850.00
4444 Circular Saw 150 150 0 45.00 125.00
5555 Cordless Screwdriver Kit 10 10 0 250.00 299.00
6666 Keurig Programmable Single-Serve 2 2 0 150.00 179.00
7777 Moen Chrome Kitchen Faucet 1 1 0 90.00 104.00
8888 Electric Pressure Washer 0 0 0 150.00 189.00
Total number of items in store: 308
Total inventory: $: 48400.0
Here is my code:
public void endOfDay(PrintWriter outFile)
{
outFile.println (nItems + " items are currently available for purchase in Joan's Hardware Store.");
outFile.println("----------Joan's Hardware Store-----------");
outFile.printf("itemID, itemName, pOrdered, pInStore, pSold, manufPrice, sellPrice");
for (int index = 0; index < nItems; index++)
{
outFile.printf("%n %-5s %-32s %d %d %d %.2f %.2f%n", items[index].itemID , items[index].itemName , items[index].numPord ,items[index].numCurrInSt , items[index].numPSold , items[index].manuprice , items[index].sellingprice);
}
outFile.println("Total number of items in store: " + getTotalOfStock());
outFile.println("Total inventory: $: " + getTotalDollarValueInStore());
} // end endOfDay
Thanks for any help! I have tried many things for hours!!
Basically, you need to format your header the same way you format your lines, for example...
System.out.println("----------Joan's Hardware Store-----------");
System.out.printf("%-6s %-32s %-8s %-8s %-5s %-10s %-8s%n", "itemID", "itemName", "pOrdered", "pInStore", "pSold", "manufPrice", "sellPrice");
System.out.printf("%-6s %-32s %-8d %-8d %-5d %-10.2f %-8.2f%n", "1111", "Dish Washer", 20, 20, 0, 250.50, 550.50);
Results in...
----------Joan's Hardware Store-----------
itemID itemName pOrdered pInStore pSold manufPrice sellPrice
1111 Dish Washer 20 20 0 250.50 550.50