Click here to Skip to main content
15,881,700 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
like the value of factorial number 12 is 479001600 but on console window i want to print only first 4 digit not whole number,like from 479001600 to 4790 only.how can i print first 4 digits?
Posted

The simplest way is with Substring, but you need to be sure you have at least four digits before you use it.


One of the harder ways is:

int x = 479001600 ;
int y = (int) System.Math.Log10 ( x ) ;
int z = (int) ( x / System.Math.Pow ( 10 , ( y - 3 ) ) ) ;
 
Share this answer
 
v2
You should simply be able to convert the int/decimal to a string and subsequently use sub-string function i.e.,

C#
int i = 12;
long factorial = fact(i); //assuming this gives 479001600 

string FirstFourDigits = factorial.ToString(); 

if(FirstFourDigits.Lenght >= 4)
{
  Console.WriteLine(FirstFourDigits.Substring(0, 4));
}
else
{
  Console.WriteLine(FirstFourDigits);
}


And this should be it

Regards
Pawan
 
Share this answer
 
C#
int t = 554344589;
            Response.Write(Convert.ToString(t).Substring(Convert.ToString(t).Length - 4).PadRight(Convert.ToString(t).Length, ' '));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900