numberFormat

numberFormat - DecimalFormat fmt = new...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
NumberFormat/DecimalFormat classes DecimalFormat and NumberFormat can be used to format output of numbers. They are defined in java.text package, thus this package needs to be imported at the top of the programs: import java.text.DecimalFormat; import java.text.NumberFormat; Alternatively, we can import all classes defined in the package at one using "*": import java.text.*; NumberFormat We can print numbers as dollar amounts or percent. To print a number as a dollar amount: NumberFormat money = NumberFormat.getCurrencyInstance(); double num = 3.1234; System.out.println(money.format(num)); will print out "$3.12". To print a number as a percentage: NumberFormat percent = NumberFormat.getPercentInstance(); double num2 = 0.06; System.out.println(percent.format(num2)); will print out "6%". DecimalFormat If we want only two digits to the left of the decimal point to appear for numbers, we can use DecimalFormat as follows: First we need to instantiate a DecimalFormat object:
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: DecimalFormat fmt = new DecimalFormat("0.00"); Note that "fmt" is a variable and another name can be chosen. The string "0.00" is setting to have only two decimal places. double number = 3.1234; System.out.println(fmt.format(number)); will print out "3.12". Instead of using "0.00" format, we can choose to use "0.##" format. In this case, trailing zero is not printed. DecimalFormat fmt2 = new DecimalFormat("0.##"); double number2 = 3.40; Sysmtem.out.println(fmt2.format(number2)); will print out "3.4" Using the "0.00" format, 3 will be printed as 3.00 2.147 will be printed as 2.15 4.10 will be printed as 4.10 Using the "0.000" format, 3 will be printed as 3.000 2.147 will be printed as 2.147 4.10 will be printed as 4.100 Using the "0.##" format, 3 will be printed as 3 2.147 will be printed as 2.15 4.10 will be printed as 4.1 actual number "0.00" "0.000" "0.##" 3 3.00 3.000 3 2.147 2.15 2.147 2.15 4.10 4.10 4.100 4.1...
View Full Document

This note was uploaded on 11/09/2010 for the course CSE 71682 taught by Professor Nakamura during the Spring '10 term at ASU.

Page1 / 2

numberFormat - DecimalFormat fmt = new...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online