Convert a string to Double in C# [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I just wrote a method to convert a string to double. It does what it's suppose to do, but it seems too long and I'm thinking there's a better way of writing it. Please review and suggest a better way or point out why this is not good for production code.
static double ConvertStringToDouble(string input, int rounding)
{
string[] split = input.Split('.');
double wholeNumber = 0.0;
if (split.Length > 0 && Int32.TryParse(split[0], out int temp))
wholeNumber = (double)temp;
double decimalNumber = 0.0;
if (split.Length > 1)
{
string decimalString = (split[1].Length < rounding) ? split[1] : split[1].Substring(0, rounding);
if (Int32.TryParse(decimalString, out int dec))
decimalNumber = (double)dec / Math.Pow(10, decimalString.Length);
}
return wholeNumber + decimalNumber;
}
This is the updated method now. Thanks all for the contributions
static double ConvertStringToDouble(string input, int rounding)
{
if (double.TryParse(input, out double value))
return Math.Round(value, rounding);
else return 0.0;
}

.Net has built in functionality for this, its called Double.TryParse. Double.Parse also exists, but its recommended to use the Try variant, as it won't throw exceptions if the number is not parseable into a double. You can use the method like this
string stringToParse = "1.7346"
if (Double.TryParse(stringToParse, out double parsedDouble))
{
//do something with the double here
}
else
{
//failed to parse, error logic here
}

You can just use double.Parse and double.TryParse methods, I prefer to use them like this:
string myString = "1.05";
// This throws exception:
double myParsedDouble = double.Parse(myString);
// This gives you more control over the conversion:
double? myResult = null;
if (double.TryParse(myString, out double _myResult))
myResult = _myResult;
if (myResult == null)
{
throw new ArgumentException("Not a valid double!");
}

Related

Best way for user to control integer [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
The community is reviewing whether to reopen this question as of 2 years ago.
Improve this question
I cooked this up and was wondering if there is a better way to do this.
```Console.WriteLine("Name me.");
String cn = Console.ReadLine();
Console.WriteLine($"I like this name ,{cn}, What is my funcion? ");
String fn = Console.ReadLine();
Console.WriteLine($"I will learn how to do {fn} for you.");
Console.WriteLine("I Will double any number you give me.");
int a = Convert.ToInt32(Console.ReadLine());
int b = 2;
Console.WriteLine(a * b);
```
"Best" is subjective, but there are a few problems with the code:
Any non-number string entered will throw an exception
Any decimal number string will also throw an exception.
Instead of using Convert.ToInt32, you should consider using the TryParse method instead. This method takes in a string and an out parameter that gets set to the converted value if it's successful (otherwise 0), and it returns a bool that indicates success. If we use the decimal type, we will end up with a number that has very good precision and can include decimals.
If we then create a method with a loop that uses the result of TryParse as a condition, we can loop until the user enters a correct number.
We could also allow the user to pass in a validation method, so that they can specify what the rules are for a "valid" number (i.e. if it must be greater than zero, or must be odd, etc.).
Then we might end up with something like this:
public static decimal GetDecimalFromUser(string prompt,
Func<decimal, bool> validator = null)
{
bool isValid = true;
decimal result;
do
{
if (!isValid)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid input, please try again.");
Console.ResetColor();
}
else isValid = false;
Console.Write(prompt);
} while (!decimal.TryParse(Console.ReadLine(), out result) &&
(validator == null || !validator.Invoke(result)));
return result;
}
Similarly, we can write code that prompts the user for string input. This will save us a few lines of code in our Main method, because we don't have to keep writing Console.WriteLine and Console.ReadLine:
public static string GetStringFromUser(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
Now we can write code where the user cannot enter invalid input! In use, the code would then look like:
string name = GetStringFromUser("Please give me a name: ");
string fn = GetStringFromUser($"I like this name, {name}. What is my function? ");
Console.WriteLine($"I will learn how to do {fn} for you.");
decimal input = GetDecimalFromUser("Please enter a number and I will double it: ");
Console.WriteLine($"{input} * 2 = {input * 2}");

Creating overload methods [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to create an overload method in visual studio with the method name getPrice(), here is the first overload method I tried to create:
private double getPrice(double price)
{
int intQty = 1;
txtQty.Text = intQty.ToString();
double dblSalesTax = 0;
lblSalesTax.Text = dblSalesTax.ToString();
double dblPrice = double.Parse(txtPrice.Text);
txtPrice.Text = dblPrice.ToString("c");
}
However my naming of it is off or something it keeps giving me an error, not all code paths return a double.. so I'm not sure how to fix that and this first overload method is supposed to only take a single parameter called price and then it is supposed to default Qty to 1 and sales tax to 0, besides the error did I do any of that other stuff correct or is the whole thing wrong or how would I fix that? Once I get this first parameter set I think I can get the other 2 working.
EDIT
Ok I changed it a bit...
private void btnCalculate_Click(object sender, EventArgs e)
{
getPrice(double price);
}
private double getPrice(double price)
{
double dblQty = 1;
double dblSalesTax = 0;
double dblPrice = double.Parse(txtPrice.Text);
double dblTotal = (dblPrice * dblQty) *dblSalesTax;
lblTotal.Text = dblTotal.ToString("c");
return dblTotal;
//lblSalesTax.Text = dblSalesTax.ToString();
//double dblPrice = double.Parse(txtPrice.Text);
//txtPrice.Text = dblPrice.ToString("c");
}
There is what I have now, how can I use the parameter price with it and why does it error when i try to put it in the btnCalculate_Click method?
You dont require parameter. You are not using the passed value inside function. You can return double value as given below:
`
private double getPrice()
{
int intQty = 1;
txtQty.Text = intQty.ToString();
double dblSalesTax = 0;
lblSalesTax.Text = dblSalesTax.ToString();
double dblPrice = double.Parse(txtPrice.Text);
txtPrice.Text = dblPrice.ToString("c");
return Convert.ToDouble(txtPrice.Text);
}
`

How to return multiple values in C# 7? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Is it is possible to return multiple values from a method natively?
What do you mean by natively?
C# 7 has a new feature that lets you return more than one value from a method thanks to tuple types and tuple literals.
Take the following function for instance:
(string, string, string) MyCoolFunction() // tuple return type
{
//...
return (firstValue, secondValue, thirdValue);
}
Which can be used like this:
var values = MyCoolFunction();
var firstValue = values.Item1;
var secondValue = values.Item2;
var thirdValue = values.Item3;
Or by using deconstruction syntax
(string first, string second, string third) = MyCoolFunction();
//...
var (first, second, third) = MyCoolFunction(); //Implicitly Typed Variables
Take some time to check out the Documentation, they have some very good examples (this answer's one are based on them!).
You are looking for Tuples. This is an example:
static (int count, double sum) Tally(IEnumerable<double> values)
{
int count = 0;
double sum = 0.0;
foreach (var value in values)
{
count++;
sum += value;
}
return (count, sum);
}
...
var values = ...
var t = Tally(values);
Console.WriteLine($"There are {t.count} values and their sum is {t.sum}");
Example stolen from http://www.thomaslevesque.com/2016/07/25/tuples-in-c-7/
You can also implement like this:
public class Program
{
public static void Main(string[] args)
{
var values=GetNumbers(6,2);
Console.Write(values);
}
static KeyValuePair<int,int> GetNumbers(int x,int y)
{
return new KeyValuePair<int,int>(x,y);
}
}

How to implement DateTime [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Can anyone please show me how do I implement DateTime on this code? Tried to google around but still confusing on this code.
public double CalcLastCouponDate(DateTime dtmBaseDate, DateTime dtmLastDate, int intCouponTermMonths, int intFixedCouponDay, string strOddLastCouponType)
{
int i = 0;
DateTime dtmLastCoupon;
{
if (strOddLastCouponType == "S")
{
return dtmLastCoupon = DateAdd("M", -intCouponTermMonths, dtmLastCoupon); // How to convert DateAdd to C#
}
else
{
return dtmLastCoupon = DateAdd("M", -2 * intCouponTermMonths, dtmLastCoupon); // How to convert DateAdd to C#
}
}
}
public bool IsEndDayofMonth(DateTime DateIn)
{
int intLastDay = 0;
bool IsEndDay = false;
intLastDay = CalcEndDayofMonth(Year(DateIn), Month(DateIn)); // Convert Year, Month to C#
if (intLastDay == Day(DateIn)) // Convert Day to C#
{
IsEndDay = true;
}
else
{
IsEndDay = false;
}
return IsEndDay;
Assuming DateAdd has normal semantics it would probably look something like this:
public DateTime CalcLastCouponDate(DateTime dtmBaseDate, DateTime dtmLastDate, int intCouponTermMonths, int intFixedCouponDay, string strOddLastCouponType)
{
return (strOddLastCouponType == "S") ?
dtmLastDate.AddMonths(-intCouponTermMonths) :
dtmLastDate.AddMonths(-2 * intCouponTermMonths);
}
public bool IsLastDayOfMonth(DateTime dateIn)
{
return dateIn.Day == DateTime.DaysInMonth(dateIn.Year, dateIn.Month);
}
Etc.
can u give a clear idea what you are trying to achieve.
have a look on the below links I think you may find your need.
Custom date time formats
DateTime methods

C# - Operator Return type [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to make some math operations like : a+b , a-b, a/b, a*b and so on.
I want to know if there exists Operator return type, so when I call the method (that returns the operator) to use that returned data (so the operator).
If doesn't exist how can I get that operator from a string. For instance:
string myOperator = "+";
int a = 5, b = 10;
int outcome = 0;
I need to make :
outcome = a + b;
So I need that + operator. What should I use as return type if I make a method that gives me somehow that operator?
No, there is no return type for an operator. However, you can use Func<T1,T2,R> to make a functor that has the behavior of the operator, but has the syntax of a function.
Func<int,int,int> myOperator1 = (x,y) => (x+y);
Func<int,int,int> myOperator2 = (x,y) => (x-y);
int a = 5, b = 10;
int outcome1 = myOperator1(a, b); // Returns 15
int outcome2 = myOperator2(a, b); // Returns -5
There is no such thing operator return type in C#. You need to parse the operator manually in C#. See this http://www.c-sharpcorner.com/UploadFile/patricklundin/MathExpParser12062005062213AM/MathExpParser.aspx or create your own parser.
int a = 3, b = 7;
Operator(a, b, "+"); // 10
int Operator (int op1, int op2, string op)
{
if (op == "+") return op1 + op2;
if (op == "-") return op1 - op2;
if (op == "*") return op1 * op2;
if (op == "/") return op1 / op2;
throw new ArgumentException("Specify a valid operator", "op");
}
Is your question.. how do I parse my intended operator, expressed as a string?
Grossly oversimplified... but maybe something like this?
int fuzzyMath(int a, int b, string literalOperator) {
string cleanedOperator = literalOperator.Trim();
if ("+".Equals(cleanedOperator )) {
return a+b;
} else if ("-".Equals(cleanedOperator )) {
return a-b;
} //and so on
}
Im not sure you can derive an operator as a type, or value that can freely be used in an expression, but you can test for expected literal values and compute based on that...

Categories