/*
 * @topic T01305 NumberFormat rounding
 * @brief Miscellaneous rounding examples
*/
package pckg;
/* NumberFormat rounding a double and creating a String.
 * The numbers are rounded by "half-even" algorithm, which rounds up
 * if the digit before the truncation is odd, and rounds down if the
 * digit before the truncation is even.
 * 
 * If currency format is used for 123.455, the formatted result
 * is $123.46. If the value is 123.445 the formatted result is 123.44.
 * Although this is OK for many applications, it can cause problems in others.
 *
 * If you want to round currency to the closest penny, then using the 
 * Math.round method before using the format method of the NumberFormat
 * object may produces the desired result.
 */
import java.text.NumberFormat;

public class NumberFormatDemo
{
	public static void main(String args [])
	{
		System.out.println("Using NumberFormat Rounding\n");
		
		NumberFormat curr = NumberFormat.getCurrencyInstance();
		        
		System.out.println("123.455 = " + curr.format(123.455) + " per textbook pg 106\n");
		
		System.out.println("123.445 = " + curr.format(123.445) + " per textbook pg 106\n");
		
		System.out.print("Using Math.round before using NumberFormat ");
		System.out.println("to insert commas and the dollar sign\n");
		 
		double d1 = 123.455, d2 = 123.445;
		
		double result = Math.round(d1 * 100.0) / 100.0;
		
		System.out.println(d1 + " rounded = " + result + " using Math.round\n");
		
		System.out.println(d1 + " rounded & formatted = " + curr.format(result) + "\n");
		
		       result = Math.round(d2 * 100.0) / 100.0;
		
		System.out.println(d2 + " rounded = " + result + " using Math.round\n");
		
		System.out.println(d2 + " rounded & formatted = " + curr.format(result) + "\n");			
	}			
	
}

/*
123.455 = $123.46 per textbook pg 106

123.445 = $123.44 per textbook pg 106

Press any key to continue...

*/