简体   繁体   中英

Good way to translate numeric to string, with decimal point removed?

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!

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();

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.

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, "")
}

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.

但是通常,当它来自sql server时,您不应该首先将其转换为字符串,而不是将其转换为整数/双精度,而应将其直接从row [“ column1”]中的对象转换为所需的值,这样可以避免麻烦的区域性并提高性能一点点

字符串结果= Regex.Replace(原始,“ [^ 0-9]”,“”);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM