Question

I have to deal with a numeric value (coming from a SQL Server 2005 numeric column) which I need to convert to a string, with the caveat that the decimal point has to be removed. The data itself is accessible in C# via a DataTable/DataRow.

For example, if the SQL Server column reads 12345.678, the string should be "12345678" when all is said and done. Would it be possible to point me toward a good approach for this? Maybe there's a .Net conversion method that does this, I'm not sure.

Thanks!

Was it helpful?

Solution

what about something like

var numberWithPoint = dbGetNumber();

string numberWithOutPoint = numberWithPoint.ToString().Replace(".", string.Empty);

it's quick and dirty, but it get the job done fairly simply.

OTHER TIPS

There are several possible approaches. You could convert it to a string using a specific culture so that you are sure that the period is used as decimal separator, then remove the period:

string s = num.ToString(CultureInfo.InvariantCulture).Replace(".", String.Empty);

You could use a more numeric approach to multiply the valye by 10 until there are no decimals:

while (num != Math.Floor(num)) num *= 10.0;
string s = ((int)num).ToString();

you can do it in c# like:

var myNum = 12345.678;
var myString = myNum.ToString().Replace(".","");

in sql server, you can do it like:

SELECT REPLACE( cast(myCol as varchar), '.', '') as FormattedNumber 
FROM ...

What about:

// using System.Globalization;
SqlCommand cm = new SqlCommand("SELECT 12345.678 as decimal");
// ...
SqlDataReader dr = cm.ExecuteReader();
if(dr.Read())
{
    string value = dr.GetValue(0).ToString()
        .Replace(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator, "")
}

but usually when it comes from sql server, you should not convert it first to a string than to integer / double but convert it directly from object in row["column1"] to needed value, this will save you troubles handling cultures and improve performance a bit

A straightforward method is to use

string result = original.Replace(".", "")

There might be a faster method, but if this isn't in a tight inner loop, Replace should work fine.

EDIT: Fixed code example, plus:

To address culture concerns, one might use NumberFormatInfo.NumberDecimalSeparator to determine the currently defined decimal separator.

string result = Regex.Replace(original, "[^0-9]", "");

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top