I want to convert numeric data with comma to Double. I have a datatable with multiple columns, there are columns that contain integers and/or strings, I do not want to convert those columns, I only want to convert the numbers that contain a comma. I would like to do it in a generic way if possible, in case more columns are added in the future, but taking those precautions.
foreach (DataRow row in io_dtReportPrices.Rows)
{
foreach (DataColumn col in io_dtReportPrices.Columns)
{
String cellValue = row[col].ToString();
// if it has a dash at the end, I place it at the beginning (negative number)
if (cellValue.EndsWith("-"))
{
row[col] = "-" + cellValue.TrimEnd('-');
}
// Convert to double only numbers that contain a comma
double result;
if (Double.TryParse(cellValue, NumberStyle.Float, new System.Globalization.CultureInfo("pt-BR"), out result))
{
row[col] = result;
}
//Double.Parse(currentrow(1).ToString().Trim(), new System.Globalization.CultureInfo("pt-BR"))
}
}
But it gives me an error saying the following:
I honestly don’t know how to solve it, I searched the internet and tried what I found, but it didn’t help.
Hello @Maite_Escalada welcome to UiPath Community Forum :
Well, I don’t have fond of using Invoke Code activity as this can be achieved using UiPath Automation Activities.
Iterate Through Columns: Use a For Each activity to iterate through the columns of the DataTable.
Check for Comma: For each cell in the column, check if the value is a string and contains a comma or a hyphen. You can use the String.Contains method for this check.
Convert to Double: If the value contains a comma, use the Double.Parse or Double.TryParse method to convert the value to a double. You can then update the cell with the converted value.
Just as alternate find attached code:
foreach (DataColumn column in yourDataTable.Columns)
{
foreach (DataRow row in yourDataTable.Rows)
{
if (row[column].GetType() == typeof(string) && row[column].ToString().Contains(","))
{
double parsedValue;
if (double.TryParse(row[column].ToString().Replace(",", "."), out parsedValue))
{
row[column] = parsedjsonValue;
}
}
}
}