Trying to separate whole number and decimal asp.net c# - c#

I'm looking for guidance can someone help me out?
I need to separate the value in duration into a whole number and the decimal.
EDIT: I have a textbox in one page. If someone enters 1.5 and it gets stored in duration, I would like to retrieve that in another page and I would like to store the whole number in a textbox and the decimal number will select a value from a dropdownlist based on the response.
Sorry I added duration twice by accident.
context.Response.Write(dr["Title"].ToString()
+ '|' + dr["CourseId"].ToString() + '|' + dr["duration"].ToString()
+ '|' + dr["Code"].ToString() + '|'
+ dr["Category"].ToString() + School.NewLine);

If the value you are trying to split is a number, try this:
decimal number = 12.34;
int wholePart = decimal.Truncate(number);
decimal fractionPart = number - wholePart;
If is is a string, CLandry's answer should work, duration[0] would be the whole part and duration[1] would be the fraction part.

var duration = dr["duration"].ToString().Split(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
int durationWhole = Int32.Parse(duration[0]);
int durationDecimal = Int32.Parse(duration[1]);
Duration will be a string array. duration[0] is the part of the number before the decimal, and duration[1] is the part after.
The split is being done with the decimal separator of the culture using it, so it should work globally as well.
Based on the edit in your question, I've updated the answer to give you numerical results as well. Now you can use the numbers or strings as needed.

context.Response.Write(dr["Title"].ToString()
+ '|' + dr["CourseId"].ToString() + '|' + dr["duration"].ToString().Split('.')[0]
+ '|' + dr["duration"].ToString().Split('.')[1] + '|' + dr["Code"].ToString() + '|'
+ dr["Category"].ToString() + School.NewLine);

You could use Substrings and IndexOf:
{ context.Response.Write(
dr["Title"].ToString() + '|' +
dr["CourseId"].ToString() + '|' +
dr["duration"].ToString().Substring(0, dr["duration"].ToString().IndexOf(".")) + '|' +
dr["duration"].ToString().Substring(dr["duration"].ToString().IndexOf("."), dr["duration"].ToString().Length()) + '|' +
dr["Code"].ToString() + '|' +
dr["Category"].ToString() +
School.NewLine);
}

Related

QueryString is taking first substring and discarding rest post space

I have a query string which passes 6 parameters in C# as shown below
string url = "Report.aspx?Desc=" + Desc.SelectedValue + "&PON=" + PNumber.Text + "&InsNme=" + ins.ToUpper().ToString() + "&BackTy=" + cb.SelectedValue + "&StartDate=" + txtDate.Text + "&EndDate=" + txtTodate.Text + "&Name=" + nme;
string s = "window.open('" + url + "', 'popup_window', 'width=1500,height=800,left=200,top=150,resizable=yes');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
Now, in the above string InsNme contains a value of John Patrice Joanne. Instead of complete value of InsNme Report.aspx contains just John. How to handle this?
The spaces in the name are breaking the URL.
If you want to do it yourself, replace spaces with %20. Otherwise a simple, but not anywhere near "good" technique is:
url = "Report.aspx?";
// for each name value pair ...
url += dataLabel + "=" + System.Web.HttpUtility.UrlEncode( dataChunk ) +"&";
The utility is preferred as it will take care of other, similar issues such as literal '&' in a name.
Check this answer for better solutions.
How to build a query string for a URL in C#?

padding a string with zeros and passing it to another page in asp.net webforms

I'm trying to pad a textbox value with zeros and pass it to another page with Response.Redirect in asp.net webforms. I cannot get the number to be padded with zeros. If I enter 2 in the textbox it should display 000002 on the second page. Here's my code:
if (cmbSearchBy.Text == "Account Number")
{
var zeropadding = String.Format("{0:00000}", txtSearchKeyword.Text);
Response.Redirect("AccountTable.aspx?SearchBy=" + cmbSearchBy.SelectedValue + "&TableSelection=" + cmbSelectTable.SelectedValue + "&SearchTerm=" + zeropadding + "");
}
else
{
Response.Redirect("AccountTable.aspx?SearchBy=" + cmbSearchBy.SelectedValue + "&TableSelection=" + cmbSelectTable.SelectedValue + "&SearchTerm=" + txtSearchKeyword.Text + "");
}
Since the values are all strings, you don't need to use String.Format() like you would with numeric values. You can use the .PadLeft() method instead. Something like this:
var zeropadding = txtSearchKeyword.Text.PadLeft(6, '0');
This would pad the value with '0' on the left to a total width of 6. (Or simply return the string if it's already 6 characters or more.)

Best way to prepare values of varying types for combined hashing in C#?

I have a few values of varying types which I need to combine together before hashing to create a value that is unique to this combination. Security isn't particularly important, just that the values are guaranteed unique.
Is this a safe approach, and furthermore are there any issues with this approach that I should know about?
public string GetHash(int x, int y, DateTime z, string w)
{
string concat = x.ToString() + y.ToString() + z.Ticks.ToString() + w;
byte[] hash = hashAlgorithm.ComputeHash(Encoding.ASCII.GetBytes(concat));
return Encoding.ASCII.GetString(hash);
}
Thanks in advance!
No, it's not necessarily reliable, because the system that verifies the hash could have different culture settings. You could address this by adding CultureInfo.InvariantCulture to your ToString() calls.
using System.Globalization
...
string concat = x.ToString(CultureInfo.InvariantCulture)
+ y.ToString(CultureInfo.InvariantCulture)
+ z.Ticks.ToString(CultureInfo.InvariantCulture)
+ w;
You may also be subject to collisions, since your fields align ambiguously (e.g. "11" + "2" is the same as "1" + "12"). You can address that by adding delimiters or using a fixed width format.
string concat = x.ToString("0000000000", CultureInfo.InvariantCulture)
+ y.ToString("0000000000", CultureInfo.InvariantCulture)
+ z.Ticks.ToString("0000000000", CultureInfo.InvariantCulture)
+ w;
Or
string concat = x.ToString(CultureInfo.InvariantCulture)
+ "|"
+ y.ToString(CultureInfo.InvariantCulture)
+ "|"
+ z.Ticks.ToString(CultureInfo.InvariantCulture)
+ "|"
+ w;

How to slice/trim this value?

I am trying to remove the last 6 characters from item.Size because the data has a decimal place and 5 trailing 0s in the database.
sb.Append("<div>" + item.Size + " " + item.Units + " </div>");
ie. item.Size is displayed as 1.00000 and I need it to just be displayed as 1.
This is part of a StringBuilder, and as I'm new to coding, not even sure the right way to go about this.
sb.Append("<div>" + (int)item.Size + " " + item.Units + " </div>");
StringBuilder has the same formatting capabilities as String.Format when you use the AppendFormat method:
sb.AppendFormat("<div>{0:N0} {1} </div>", item.Size, item.Units);
The format string "N0" tells it to format the number with 0 decimal points. That assumes the item.Size is stored as a numerical type. If not, simply remove the part of the string you don't want:
sb.AppendFormat("<div>{0} {1}</div>", item.Size.Split('.')[0], item.Units);
Here I've used Split, assuming that the value is actually something like what you've shown in your example.
Better you use int.TryParse(or Int32.TryParse) method. because if item.Size is not convertible to int, then it wont give you any exception. you can use int or long according to your choice. So you can handle this in your code according to the if/else condition.
Sample Code:
int size;
string str = "";
if(int.TryParse(str, out size) == true)
{
}
else
{
}

Double ToString() no scientific notation not returning a string for 0.0

I need to return the string representation of a double in decimal notation rather than scientific and I used a modified version of the accepted solution here:
Double ToString - No Scientific Notation
private static readonly string format = "." + new string('#', 324);
foo.ToString(format);
This works well other than for a value that equals zero i.e. 0, 0.0, 0.000 etc where it returns an empty string.
What would be the easiest way to return a string representing 0 for any value of zero.
I don't mind if the string is 0 or 0.0 etc as long as it is numerical and not scientific.
Edit: I know I could add a conditional statement to check if the string is empty but I am interested to see if there is a way to do it using string formatting.
You could always add a statement like:
foo.ToString(format)
if (string.IsNullOrEmpty(foo))
foo = "0";
try this:
string format = "0." + new string('#', 324);
It will add zero before dot (if needed)
See example ideone
Maybe it's what you are looking for:
double aa = 12.33333;
string foo = String.Format("{0:0.#}", System.Convert.ToSingle(aa));
Argh, those hacks people use. To give one hack more here:
foo.ToString(format + ";" + "-" + format + ";" + "0");
or with
static readonly string newFormat = format + ";" + "-" + format + ";" + "0";
defined under format in the code source, just:
foo.ToString(newFormat);
Of course that is a constant, so it is really:
foo.ToString(.####################################################################################################################################################################################################################################################################################################################################;-.####################################################################################################################################################################################################################################################################################################################################;0);
Hope you like it (I don't).

Categories

Resources