I am trying to replace a comma in a string.
For example, the data is the currency value of a part.
Eg. 453,27 This is the value I get from an SAP database
I need to replace the comma to a period to fix the value to the correct amount. Now sometimes, it will be in the thousands.
Eg. 2,356,34 This value needs to be 2,356.34
So, I need help manipulating the string to replace comma that is 2 characters from the end.
Thanks for the help
string x = "2,356,34";
if (x[x.Length - 3] == ',')
{
x = x.Remove(x.Length - 3, 1);
x = x.Insert(x.Length - 2, ".");
}
string a = "2,356,34";
int pos = a.LastIndexOf(',');
string b = a.Substring(0, pos) + "." + a.Substring(pos+1);
You'll need to add a bit of checking for cases where there are no commas in the string, etc. but that's the core code.
You could also do it with a regex, but this is simple and reasonably efficient.
A quick google search gave me this:
void replaceCharWithChar(ref string text, int index, char charToUse)
{
char[] tmpBuffer = text.ToCharArray();
buffer[index] = charToUse;
text = new string(tmpBuffer);
}
So your "charToUse" should be '.'. If it always is 2 characters from end, your index should be
text.length - 3.
http://www.dreamincode.net/code/snippet1843.htm
If I understand correctly, you always need to replace the last comma with a period.
public string FixSAPNumber(string number)
{
var str = new StringBuilder(number);
str[number.LastIndexOf(',')] = '.';
return str.ToString();
}
string item_to_replace = "234,45";
var item = decimal.Parse(item_to_replace);
var new_item = item/100;
//if you need new_item as string
//then new_item.ToString(Format)
Use this :
string str = "2,356,34";
string[] newStr = str.Split(',');
str = string.Empty;
for (int i = 0; i <= newStr.Length-1; i++)
{
if (i == newStr.Length-1)
{
str += "."+newStr[i].ToString();
}
else if (i == 0)
{
str += newStr[i].ToString();
}
else
{
str += "," + newStr[i].ToString();
}
}
string s = str;