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

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

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]", "");

Related

Format a string like you would a numeric value

I have a string that I would like to format the same way I would a numeric value.
Ex:
int num = 2;
string option = num.ToString("000");
Console.WriteLine(option);
//output
//002
But the only way I can think to format it is to parse it as an int, then apply the ToString("000") method to it.
string option = "2";
option = int.Parse(option).ToString("000");
Is there a better, more direct way to do this?
No, there is no built-in mechanism to "format" a string as if it were a number. Some options:
Use string functions (Pad, Length, Substring) to determine what characters should be added
Parse to a numeric type and use ToString with numeric formatting strings
Use a reqular expression to extract the digits and generate a new string
There's not one "right" answer. Each has risks and benefits in terms of safety (what if the string does not represent a valid integer?), readability, performance, etc.
Would this suit your requirement?
string x = "2";
string formattedX = x.PadLeft(3, '0');
Console.WriteLine(formattedX); //prints 002

How do I trim the "0." after I do modulo 1 on a double variable

Hello everyone as the title say I want to trim the "0." after I do modulo 1 on a double variable
Example:
double Number;
Number = Convert.ToDouble(Console.ReadLine()); //12.777
test = Number % 1; //0.777
I want my output to be: 777
only using math with no
string trims and so...
Thank you all !!
and in c# please
That is just a formatting on the ToString. Take a look at all your options here
How about
.ToString(".###");
Without using any string functions!
while(Math.Round(Number-(int)Number,1)!=1)
{
Number=Number/0.1;
if(Number-(int)Number==0)break;//To cover edge case like 0.1 or 0.9
}
NOTE: Number should be of double type!
If I take your question literally, then you do not want the decimal point either, so .ToString(".###") will not get you what you want, unless you remove the first character (which is string manipulation, and you said you don't want that either).
If you want 777 in a numeric variable (not a string), then you can multiply your result by 1000, though I don't know if you'll always have exactly 3 digits after the decimal or not.
The easiest way really is just to use string manipulation. ToString the result without any formatting, then get the substring starting after the decimal. For example:
var x = (.777d).ToString();
var result = x.SubString(x.IndexOf('.') + 1);
You are certainly looking for this:-
.ToString(".###");
As correctly pointed by Marc in comments you should have everything to be in a string, because if you output that 0.777 as it really is stored internally, you'd get 8 random bytes.
Something like this:-
var num = (.777d).ToString();
var result = num.SubString(num.IndexOf('.') + 1);
The most generic way to do this would be:
using System.Globalization;
var provider = NumberFormatInfo.InvariantInfo;
var output = test.ToString(".###", provider)
.Replace(provider.NumberDecimalSeparator, String.Empty);
You can also set the NumberDecimalSeparator on a custom NumberFormatInfo, but if you set it to empty it will throw the exception "Decimal separator cannot be the empty string."

convert a double with a comma to a variable with a point to use in sql statement

I use my double in a select statement:
code:
SqlCommand command = new SqlCommand("SELECT min(Score) FROM "+ table +" WHERE [" + sportEvent + "] < (#result);", connect);
command.Parameters.AddWithValue("#result", result);
everything works fine if double result is an integer but not if result is a comma number (example 11,34) --> it should be 11.34 to work (point instead of comma)
How can I change a double 11,34 into 11.34 ?
It appears that your code sets a string parameter as a constraint for a DB value of numeric type, letting the database do the conversion. This is not a good idea, because it takes control away from your program: should DBA decide to reconfigure your backend database to "understand" commas instead of dots, your program will stop working!
Currently, your double is in a locale-specific format. You need to parse it using the locale-specific format provider, and then set the value that you get back from the parser as the parameter of your SQL query. Assuming that the current culture is one that is using commas as decimal separator, you can do this:
command.Parameters.AddWithValue(
"#result"
, double.Parse(s, CultureInfo.CurrentCulture)
);
You can use this
result.ToString(CultureInfo.InvariantCulture)
You could try changing the variable into string:
result.ToString().Replace(',','.');
This will replace the comma with a dot.
If result is Double then:
command.Parameters.Add("#result", SqlDbType.Float).Value = result

Failed to convert parameter value from a String to a Decimal

Im importing a csv to my sql server table using the following code
SqlCommand nonqueryCommand = myConnection.CreateCommand();
nonqueryCommand.CommandText =
"INSERT INTO MYTABLE VALUES(#num1, #num2,#num3,#num4)";
nonqueryCommand.Parameters.Add("#num1",SqlDbType.Decimal);
nonqueryCommand.Parameters.Add("#num2", SqlDbType.Decimal);
nonqueryCommand.Parameters.Add("#num3", SqlDbType.Decimal);
nonqueryCommand.Parameters.Add("#num4", SqlDbType.Decimal);
nonqueryCommand.Parameters["#num1"].Value = crntRecord[0];
nonqueryCommand.Parameters["#num2"].Value = crntRecord[1];
nonqueryCommand.Parameters["#num3"].Value =crntRecord[3];
nonqueryCommand.Parameters["#num4"].Value = crntRecord[4];
nonqueryCommand.ExecuteNonQuery();
where the parameter 3 and 4 are of type decimal(9,6) in the DDL when i execute the code at ExecuteNonQuery i get the following exception
Failed to convert parameter value from a String to a Decimal.
please help me find out the problem tnx.
EDIT
the value in the crntRecord[3] looks like
Assuming that crntRecord is an array of strings, you need to parse the strings to a decimal first.
Ex:
nonqueryCommand.Parameters["#num3"].Value = decimal.Parse(crntRecord[3].ToString());
Note that this will throw an exception if crntRecord[3] is not parseable to a decimal; if that's a situation that could occur, look into decimal.TryParse() instead.
Edited to use safer parsing methods
Your strings have surrounding quotes that you need to strip off. Try
decimal num3;
bool isDecimal = decimal.TryParse(crntRecord[3].Trim(new []{'\"'}), out num3);
if(isDecimal)
nonqueryCommand.Parameters["#num3"].Value = num3;
I would recommend using this method for all of your decimals, which would mean putting this logic in a reusable function would be a rise refactoring.
try with
nonqueryCommand.Parameters["#num1"].Value = Convert.ToDecimal(crntRecord[0]));
nonqueryCommand.Parameters["#num2"].Value = Convert.ToDecimal(crntRecord[1]);
nonqueryCommand.Parameters["#num3"].Value =Convert.ToDecimal(crntRecord[3]);
nonqueryCommand.Parameters["#num4"].Value = Convert.ToDecimal(crntRecord[4]);
Use
nonqueryCommand.Parameters.AddWithValue("#num1", crntRecord[0]);

Get characters behind the dot in of a double

I feel like this is a very noob question.. but I just can't get the right statement for it.
For display purposes, I want to split a double in two: the part before the dot and the first two digits after the dot. I need it as a string. Target language: C#.
E.g.: 2345.1234 becomes "2345" and "12"
I know how to get the part before the dot, that's simply:
Math.Floor(value).ToString()
...but what is the right way to get the part "behind the dot"?
There must be some nice way to do that in a simple way...
I can't think of anything else then:
Math.Round(100 * (value - Math.Floor(value))).ToString("00");
I'm sure there is a better way, but I just can't think of it. Anyone?
Regular expressions (regex) is probably you best bet, but using the mod operator may be another valuable solution...
stuffToTheRight = value % 1
Cheers.
//
//Use the Fixed point formatting option. You might have a bit more work to do
//if you need to handle cases where "dot" is not the decimal separator.
//
string s = value.ToString("F2", CultureInfo.InvariantCulture);
var values = s.Split(".");
string v1 = values[0];
string v2 = values[1];
See this link for more about formatting: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
Here is some untested code that tries to take current culture into account:
//
//Use the Fixed point formatting option.
//
string s = value.ToString("F2", CultureInfo.CurrentCulture);
var values = s.Split(CultureInfo.NumberFormat.NumberDecimalSeparator);
string v1 = values[0];
string v2 = values[1];
use regex ".[0-9][0-9]"
In one line it will be:
string[] vals = value.ToString("f2").Split(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.ToCharArray());
vals[0] : before point.
vals[1] : after point.

Categories

Resources