Formatting Numbers and Splitting Strings

Download Report

Transcript Formatting Numbers and Splitting Strings

import java.text.*; //Needed to format numbers to 2 places
// Use the DecimalFormat class to define a format
DecimalFormat currFormat =
new DecimalFormat("$###,###.##"); // Currency format
DecimalFormat decFormat =
new DecimalFormat("######.##"); // 2 decimal places
double totMoney = 2000.55999999998;
// Use the DecimalFormat.format() method. It returns a String.
// Convert it to double with Double.valueOf() method
double totalMoney = Double.valueOf(decFormat.format(totMoney));
String totalCurrency = currFormat.format(totMoney);
System.out.println("totalMoney = "+totalMoney);
System.out.println("totalCurrency = "+totalCurrency);
When formatting 2000.55999999998:
// The following is output to the console:
totalMoney = 2000.56
totalCurrency = $2,000.56
String s = "one two four five";
String[] words = s.split(" ");
OUTPUT
System.out.println(words[0]);
one
System.out.println(words[1]);
two
System.out.println(words[3]);
five
String s = "one
five";
two four
Tabs between the words
String[] words = s.split("\\t");
OUTPUT
one
System.out.println(words[0]);
two
System.out.println(words[1]);
five
System.out.println(words[3]);