7. Printing output in different formats (say rounding up to 5 decimal places, truncating after 4 decimal places, padding zeros to the right and left, right and left justification)(Input output operations)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace lrn2CSharp7
{
class Program
{
static void Main( string[ ] args )
{
double theNumber;
Console.WriteLine( "Input a number to be formatted" );
Console.Write( ":" );
try
{
theNumber = Convert.ToDouble( Console.ReadLine( ) );
Console.WriteLine( "Original number: {0}", theNumber );
Console.WriteLine( "Rounded up to the 5th decimal place: {0}", Math.Round( theNumber, 5 ) );
Console.WriteLine( "Truncating after the 4th decimal place: {0}", Decimal.Truncate( Convert.ToDecimal( theNumber * 10000 ) ) / 10000 );
Console.WriteLine( "Padding 7 zeroes on each side: {0}", String.Format( "{0:0000000.0000000}", theNumber ) );
Console.WriteLine( "Here is a box with 20 spaces: | |" );
Console.WriteLine( "Here is the number left justified: |{0,-20}|", theNumber );
Console.WriteLine( "Here is the number right justified: |{0,20}|", theNumber );
}
catch ( FormatException fe )
{
Console.WriteLine( "You did not enter a valid number fool." );
}
Console.WriteLine( "Press esc to exit." );
while ( !keyPressHandler( Console.ReadKey( true ) ) )
{
Thread.Sleep( 250 );
/* no op */
}
}
protected static Boolean keyPressHandler( ConsoleKeyInfo input )
{
if ( input.Key == ConsoleKey.Escape )
return true;
return false;
}
}
}
posted by dharh 9:56 PM Dec 5th, 2009