Click here to Skip to main content
15,894,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Actually i have the value "000000099"
and after some trimming methods the value finally get displayed as ".99"
Here actually trimming the front all zero's and displaying from DOT(front all 0's are removed or trimmed) i.e; finally it displays as ".99"

So here i need, if the value less than 1 like "0.99" or "0.73" or "0.35"
it should get displayed as "0.99 or 0.73"
but not like ".99 or .73"
Please Help me out with this friends...........!!

What I have tried:

C#
public string FormateStringAmount( string strValue ) // here string value is getting like 0000000099 for 0.99 value
{
try
{
if (strValue.Trim () =="" ) return "0.00" ;

string strTrimString = strValue.Trim(); 		
string strAmount  = "0.00";
int intLength =strTrimString.Length ;

if ( strTrimString.EndsWith("+")  )
  {
    strAmount =  strTrimString.Substring(0,intLength -3)+"." + 
    strTrimString.Substring( intLength -3,2) ;
  }
else if (  strTrimString.EndsWith("-"))
  {
    strAmount =  strTrimString.Substring(0,intLength -3)+"." + 
    strTrimString.Substring( intLength -3,2)+"-" ;
  }
else
  {
    strAmount = strTrimString.Substring(0,intLength -2)+"." + 
    strTrimString.Substring( intLength -2,2);
  }

  strAmount = strAmount.TrimStart ('0');// here the value is getting trimmed front Zero's
   if (strAmount.Equals (".00") || strAmount.Equals (".00-"))  
   strAmount ="0.00" ;
   return strAmount;
    }
	Catch (Exception)
	{	 
	return strValue;
	}
}
Posted
Updated 3-Jan-18 20:38pm
v2

Please, read this:
Standard Numeric Format Strings | Microsoft Docs[^]
Custom Numeric Format Strings | Microsoft Docs[^]

A proper way to get numeric value is to convert string into double by using Double.Parse method, then to display it by using ToString() method. For example:

C#
string stramount = "000000099";
double dblamount = Double.Parse(stramount, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture);
dblamount /= 100;
Console.WriteLine(dblamount.ToString("0.00")); //displays 0.99


Good luck!
 
Share this answer
 
v2
I understand your requirement like this :
- You have allways a string which only contains numbers.
- You allways want to have the last 2 numbers of the string as decimals.

So your code could look like this :
C#
string s = "000000099";
int i = (int)s;
double d = (double)i / 100;
string s2 = d.ToString("0.00");

I have done it in steps so you could see how it works.
The code itself could be compressed ...
 
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