How to call .cs file from a .aspx.cs in asp.net - c#

Is it possible to store this method with labels in class file?
Example:
aspx.cs
private void addSalat()
{
decimal sum= Convert.ToDecimal(Label6.Text);
decimal sum2= Convert.ToDecimal(Label17.Text);
decimal sum3= Convert.ToDecimal(Label54.Text);
decimal sum4= Convert.ToDecimal(Label66.Text);
decimal sum5= Convert.ToDecimal(Label78.Text);
decimal sum6= Convert.ToDecimal(Label90.Text);
decimal sum7= Convert.ToDecimal(Label102.Text);
decimal sum8= Convert.ToDecimal(Label114.Text);
decimal sum9= Convert.ToDecimal(Label126.Text);
decimal sum= sum+ sum2+
sum3+ sum4+ sum5+ sum6+ sum7+ sum8
+ sum9;
Label42.Text = sum.ToString();
}
//do calculations here and call this method in aspx.cs file, i dont't know how to put here labels if is possible:
public class Class1
{
public void Sum()
{
decimal sum= Convert.ToDecimal(Label6.Text);
decimal sum2= Convert.ToDecimal(Label17.Text);
decimal sum3= Convert.ToDecimal(Label54.Text);
decimal sum4= Convert.ToDecimal(Label66.Text);
decimal sum5= Convert.ToDecimal(Label78.Text);
decimal sum6= Convert.ToDecimal(Label90.Text);
decimal sum7= Convert.ToDecimal(Label102.Text);
decimal sum8= Convert.ToDecimal(Label114.Text);
decimal sum9= Convert.ToDecimal(Label126.Text);
decimal sum= sum+ sum2+
sum3+ sum4+ sum5+ sum6+ sum7+ sum8
+ sum9;
Label42.Text = sum.ToString();
}
}

You would have to do something like this:
private decimal Sum(decimal firstValue, params decimal[] moreValues)
{
decimal val = firstValue;
return val + moreValues.Sum(); // Note this is not recursion. It is calling the LINQ Sum() function.
}
And call it like this:
Sum(5.2); // returns 5.2
Sum(6, 10); // returns 16
Sum(1,2,3); // returns 6
Or something like this:
decimal sum = Sum(Convert.ToDecimal(Label6.Text),
Convert.ToDecimal(Label17.Text),
Convert.ToDecimal(Label54.Text)
// and so forth
);

I would just leave it in the code-behind of the page. Since you're basically just adding values there's not a lot to gain by splitting it into a different class. If you were doing more complex calculations that needed unit testing, etc. then I would consider splitting it out.
You could also make the code a little cleaner by using Linq to sum the values:
decimal sum = new [] {Label6, Label17, Label54, Label66, Label78, Label90, Label102, Label114, Label126}
.Sum(lbl => Convert.ToDecimal(lbl.Text));

Related

Rounding to midpoint of decimal place using ToString only

I know that C# has some options to format decimal numbers with some extended logic in the ToString() method, as e.g.
double d1 = 1.3333;
double d2 = 1.6666;
string d1Str = d1.ToString("#0.00"); // 1.33
string d2Str = d2.ToString("#0.00"); // 1.67
That's great, my number is rounded to the second decimal. But what if I wanted to round to a step of 0.05 instead of 0.01? Is there a way to use the ToString() method in a similar way to round the value not to a given step-size (e.g. 0.05)?
Note: I know I could do something like this:
(Math.Round(1.33333*20)/20).ToString();
but the question is about getting this result using ToString() only.
Is it possible for you to create an extension overload for ToString() for these components?
If so you could write something like:
public static class DoubleStaticExtension
{
public static string ToString(this double value, string format, int decimalToRoundHalfwayAt)
{
int modifier = 2 * (int)Math.Pow(10, decimalToRoundHalfwayAt -1 );
return (Math.Round(value * modifier, MidpointRounding.AwayFromZero) / modifier).ToString(format);
}
}
Calling that with
double d = 9.333333;
string result = d.ToString("#0.00", 2);
Would give a result of 9.35
And
double d = 9.333333;
string result = d.ToString("#0.00", 1);
Would give a result of 9.50

trying to create a extension method to convert from string to decimal

I'm trying to come up with a global way of converting a string to X number of decimal places and I'm having no luck. I need this to return a decimal with X number of decimals.
Here is what I have so far but I cannot figure out how to get it to know what to divide by easily:
public static decimal ToXDecimalPlaces(this object value, int numberofdecimalplaces, decimal defaultValue = 0)
{
double retval;
if (double.TryParse(value.ToString(), out retval))
{
return (decimal)(retval / 10);
}
return defaultValue;
}
So if I send it:
value = "12345"
value.ToXDecimalPlaces(2)
I'd like to get back:
123.45
etc.
The division of the retval needs to be different pending on the numberofdecimalplaces.
Any suggestions? I would prefer not to have to create a handful of extension methods or is that what I should do?
Should I just create:
To1DecimalPlaces
To2DecimalPlaces
To3DecimalPlaces
etc
For each one I need and move on?
How about using Math.Pow?
Something like
return (decimal)(retval / Math.Pow(10, numberofdecimalplaces));

Remove Insignificant decimal places when converted to string (C#)

I have a property which has decimal datatype let's say "Interest" then I have another property of string type let's say "InterestString".
Properties
public decimal Interest { get; set; }
public string InterestString { get; set; }
I want to assign the value of Interest to InterestString so I did the following. For example lets assume Interest has a value of 4 (without decimal places):
InterestString = Interest.ToString();
If the conversion finished my InterestString becomes "4.000" but the value of my Interest is only 4 without .0000.
I want to retain the format even after conversion. How can I get rid of those insignificant decimal places?
If I do something like this
InterestString = Interest.ToString("N0");
It will give me InterestString="4";But what if I have Interest 4.5? This will give meInterestString = "5"` (rounded to ten).
If I do Interest.ToString("N2") that would give me still 2 insignificant decimal places. The behavior that I want is remove the insignficant decimal places.
Please help.
I don't think System.Decimal has a Normalize method, which is basically what you want. If you know how many decimal places you want at most you can use:
string x = Interest.ToString("0.######");
with as many # signs as you're interested in. Only significant digits will be filled in:
using System;
class Test
{
static void Main()
{
ShowInterest(4m); // 4
ShowInterest(4.0m); // 4
ShowInterest(4.00m); // 4
ShowInterest(4.1m); // 4.1
ShowInterest(4.10m); // 4.10
ShowInterest(4.12m); // 4.12
}
static void ShowInterest(decimal interest)
{
Console.WriteLine(interest.ToString("0.#####"));
}
}

converting double/floating to integer in C#

My question might looks like silly, but i struck with it.
I have a string value "155.300" and i want to convert it to integer.
I tryed but throwing System.FormatException....pls someone help me out.
Since your source data is string you need to Convert it to Double first then just cast it to int or use Convert.ToInt32, but remember Convert.ToInt32 rounds it to nearest integer number, whereas casting takes the int part of the number (truncate)
double d = Convert.ToDouble("155.00");
int a = (int) d;
int b = Convert.ToInt32(d);
Or in a single Line
int b =(int) Convert.ToDouble("155.000");
EDIT
Since you want to use decimal point as thousand separator, I believe in German culture you can try the following.
int b = ((int)Convert.ToDouble("154.500", new CultureInfo("de-DE")));
That will give you 154500
EDIT 2
Or much better is to use int.Parse with NumberStyles.AllowThousands:
int b = int.Parse("154.500", NumberStyles.AllowThousands, new CultureInfo("de-DE"));
First parse it as a decimal or double (probably best to use decimal as you've got decimal data) then either cast or use something like Math.Round, depending on your requirements.
Basically, you need to always consider what data you've got: "155.300" isn't a string representation of an integer, so don't try to parse it as an integer. Parse it as what it is, then convert that to an integer.
Alternatively, you could hack at the string representation first, but personally I find that to be a more brittle approach in many cases.
EDIT: Note that if this is really already an integer, but with a thousands separator, you don't need to use double at all - you can use int.Parse, specifying an appropriate culture and number style:
int parsed = int.Parse(text, NumberStyles.Integer | NumberStyles.AllowThousands,
culture);
Here is a working conversion sample. Take a special look with the edge conditions, the output may be different if using several rounding/casting techniques
class Program
{
public static int MyToInt(string str)
{
double result;
bool success = Double.TryParse(str, out result);
if (!success)
{
throw new ArgumentException(
"Cannot parse a string into a double");
}
return Convert.ToInt32(result); // 156
//return (int)result; // 155 <<
//return (int)Math.Round(result); // 156
}
static void Main(string[] args)
{
string s = "155.500";
int value = MyToInt(s);
}
}
You can try this:
string str = "123.123";
str = str.Remove(str.IndexOf('.'), 1);
int result;
int.TryParse(str, out result);
Edit: Based on your comment, modified to multiply by thousand.
Or you can just try:
string str = "123.123";
double result;
double.TryParse(str, out result);
int final = (int)(result * 1000);

TryParse failing with negative numbers

I'm having a problem getting TryParse to work correctly for me. I have a list of values that I am almost assured are valid (as they come from another component in our system) but I would like to make sure there is proper error handling in place.
Here is an example list of my values:
20.00
20.00
-150.00
And here is the method I originally wrote:
private decimal CalculateValue(IEnumerable<XElement> summaryValues)
{
decimal totalValue = 0;
foreach (XElement xElement in summaryValues)
{
decimal successful;
Decimal.TryParse(xElement.Value, out successful);
if (successful > 0)
totalValue += Decimal.Parse(xElement.Value);
}
return totalValue;
}
The variable 'successful' was returning false for -150.00, so I added NumberStyles:
private decimal CalculateValue(IEnumerable<XElement> summaryValues)
{
decimal totalValue = 0;
foreach (XElement xElement in summaryValues)
{
decimal successful;
Decimal.TryParse(xElement.Value, NumberStyles.AllowLeadingSign, null, out successful);
if (successful > 0)
totalValue += Decimal.Parse(xElement.Value, NumberStyles.AllowLeadingSign);
}
return totalValue;
}
However, now that I have the NumberStyles in there, none of the numbers will parse! I feel good about having IFormatProvider set to null as this is all within our system. Does anyone see what I may be doing wrong?
This is not how you are supposed to use TryParse.
TryParse returns a boolean (true/false), so your code above should be:
private decimal CalculateValue(IEnumerable<XElement> summaryValues)
{
decimal totalValue = 0;
foreach (XElement xElement in summaryValues)
{
decimal valueReturned;
bool successful = Decimal.TryParse(xElement.Value, out valueReturned);
if (successful)
totalValue += valueReturned;
}
return totalValue;
}
or more succinctly,
private decimal CalculateValue(IEnumerable<XElement> summaryValues)
{
decimal totalValue = 0;
foreach (XElement xElement in summaryValues)
{
decimal valueReturned;
if (Decimal.TryParse(xElement.Value, out valueReturned))
totalValue += valueReturned;
}
return totalValue;
}
Others are explaining how to do it right, but not really explaining what you're doing wrong.
Where you're using "successful" above isn't the success value, it's the actual number that is being parsed. So if you're parsing "-150.00" of course successful will be negative. The out value of TryParse is the actual parsed value and the boolean indicating whether the process was successful or not is the returned value. Using what you have to help understand would be something like:
string inputValue = "-150.00";
decimal numericValue;
bool isSucessful = Decimal.TryParse(inputValue , out numericValue);
In this case, isSuccessful will be TRUE, numericValue will be -150. When you're using user-provided values instead of the hardcoded one I used above you'll want to check:
if(isSuccessful)
{
// Do something with numericValue since we know it to be a valid decimal
}
else
{
// Inform User, throw exception, etc... as appropriate, Don't use numericValue because we know it's wrong.
}
The other answers have got the right idea with regard to the proper way to use Decimal.TryParse. However, if I were writing the method in question, I'd use LINQ to work with LINQ-to-XML objects:
private decimal CalculateValue(IEnumerable<XElement> summaryValues)
{
return summaryValues
.Sum(el =>
{
decimal value;
if (Decimal.TryParse(el.Value, out value))
return value;
return 0M;
});
}
This version works the exact same way, but it uses the Enumerable.Sum method to calculate the total. All I have to supply is an inline function that extracts decimal values from an XElement.
Came in from Google. Answer for me was the incoming culture was wrong - specifically in an incoming JSON file.
Use
totalValue += decimal.Parse(xElement.Value, NumberStyles.Any, CultureInfo.InvariantCulture);
or
bool successful = decimal.TryParse(xElement.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out value);
your successful is going to be negative for a negative value being parsed. your if (successful > 0) is what's tripping you up.
If they are almost positively going to be valid values, try using Convert.ToDecimal:
decimal val = Convert.ToDecimal(xElement.Value);
Otherwise, change your logic a bit to be more like:
decimal val;
if (Decimal.TryParse(xElement.Value, out val)){
// valid number
}
I would suggest you to tell XElement which node value it should look for as in:
XElement.Element("nodename").Value
Instead of XElement.Value. at least that is what I would do :)

Categories

Resources