How To Check a double value whether is Int or double - c#

Is That Any calculation or method allow me to check whether a double value is Int or Double in c# code
Example
Double NumberOne = 55.00 // Return False
Double NumberTwo = 55.10 // Return True

Use Math.Floor
if (Math.Floor(number) == number) {
// yay, an "int"
}

private bool IsDoubleNotAnInt(double num)
{
if ((num % 1) == 0)
{
return false;
}
else
{
return true;
}
}

You could check
n % 1 == 0
to determine this.

You could compare it with value without fractional part:
Math.Floor(n) != n

Related

Is there a better way to remove characters from an integer in C#?

I need to check if an integer has 6 characters, and if it does, remove the first three characters and return the resultant integer. Otherwise, just return the original integer. This is what i have, I would like to know if there is a better/faster/more efficient way in C#?
public static int MyMethod(int originalInt)
{
int outputInt = originalInt;
string temp = originalInt.ToString();
if (temp.Length == 6)
{
temp = temp.Substring(3);
if (!Int32.TryParse(temp, out outputInt))
{
outputInt = originalInt;
}
}
return outputInt;
}
Why use strings at all?
if (originalInt >= 100000 && originalInt < 1000000)
return originalInt % 1000;
return originalInt;
(Assuming originalInt is always positive)
Try This :
public static int MyMethod(int originalInt)
{
return (originalInt > 99999 && originalInt <1000000)?originalInt % 1000 : originalInt;
}
It returns the result that you need

Convert a text fraction to a decimal

Similar to this question just in C# instead of JavaScript. I couldn't find anything for C# while searching
I have a text box that will take a quantity, which is later stored as a double in a database. However it is possible that some quantities will be entered as string fractions e.g 1/2 for 0.5.
I want to be able to convert these to decimal before storing them to the database (being able to also convert back would be nice but not necessary). I want to be able to handle both fractions and mixed numbers e.g. 2 1/2 is saved as 2.5
Anybody know a way of doing this?
Try splitting it on the space and slash, something like:
double FractionToDouble(string fraction) {
double result;
if(double.TryParse(fraction, out result)) {
return result;
}
string[] split = fraction.Split(new char[] { ' ', '/' });
if(split.Length == 2 || split.Length == 3) {
int a, b;
if(int.TryParse(split[0], out a) && int.TryParse(split[1], out b)) {
if(split.Length == 2) {
return (double)a / b;
}
int c;
if(int.TryParse(split[2], out c)) {
return a + (double)b / c;
}
}
}
throw new FormatException("Not a valid fraction.");
}
Hey, it worked! Remember to check for a division by zero, too. You'll get Infinity, -Infinity, or NaN as a result.
And here is yet one more solution, but with a bit more seamless an integration:
public class FractionalNumber
{
public Double Result
{
get { return this.result; }
private set { this.result = value; }
}
private Double result;
public FractionalNumber(String input)
{
this.Result = this.Parse(input);
}
private Double Parse(String input)
{
input = (input ?? String.Empty).Trim();
if (String.IsNullOrEmpty(input))
{
throw new ArgumentNullException("input");
}
// standard decimal number (e.g. 1.125)
if (input.IndexOf('.') != -1 || (input.IndexOf(' ') == -1 && input.IndexOf('/') == -1 && input.IndexOf('\\') == -1))
{
Double result;
if (Double.TryParse(input, out result))
{
return result;
}
}
String[] parts = input.Split(new[] { ' ', '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
// stand-off fractional (e.g. 7/8)
if (input.IndexOf(' ') == -1 && parts.Length == 2)
{
Double num, den;
if (Double.TryParse(parts[0], out num) && Double.TryParse(parts[1], out den))
{
return num / den;
}
}
// Number and fraction (e.g. 2 1/2)
if (parts.Length == 3)
{
Double whole, num, den;
if (Double.TryParse(parts[0], out whole) && Double.TryParse(parts[1], out num) && Double.TryParse(parts[2], out den))
{
return whole + (num / den);
}
}
// Bogus / unable to parse
return Double.NaN;
}
public override string ToString()
{
return this.Result.ToString();
}
public static implicit operator Double(FractionalNumber number)
{
return number.Result;
}
}
And because it implements the implicit operator, it can be used simply by:
Double number = new FractionalNumber("3 1/2");
Anything that can't be parsed returns the Double constant Double.NaN. Without getting in to a laundry list of possible inputs, this worked with some basics. Feel free to tweak the class to fit your needs.
Split the string on the "/" then divide the two numbers.
public float FractionToDecimal(String input)
{
String[] fraction = input.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
if (fraction.Length != 2)
{
throw new ArgumentOutOfRangeException();
}
Int32 numerator, denominator;
if (Int32.TryParse(fraction[0], out numerator) && Int32.TryParse(fraction[1], out denominator))
{
if (denominator == 0)
{
throw new InvalidOperationException("Divide by 0 occurred");
}
return (float)numerator / denominator;
}
throw new ArgumentException();
}
You might try something like this: http://csharpeval.codeplex.com/ or this: https://github.com/Giorgi/Math-Expression-Evaluator
Both libraries are full mathematical expression evaluators written in C#. They're probably overkill for your use case, but worth mentioning for the benefit of others.
decimal re = (decimal)1/7;
works for me.

How to validate user input for whether it's an integer?

It tells me that it can't convert int to bool.
Tried TryParse but for some reason the argument list is invalid.
Code:
private void SetNumber(string n)
{
// if user input is a number then
if (int.Parse(n))
{
// if user input is negative
if (h < 0)
{
// assign absolute version of user input
number = Math.Abs(n);
}
else
{
// else assign user input
number = n;
}
}
else
{
number = 0; // if user input is not an int then set number to 0
}
}
You were probably very close using TryParse, but I'm guessing you forgot the out keyword on the parameter:
int value;
if (int.TryParse(n, out value))
{
}
Just use this:
int i;
bool success = int.TryParse(n, out i);
if the parse was successful, success is true.
If that case i contain the number.
You probably got the out argument modifier wrong before. It has the out modifier to indicate that it is a value that gets initialized within the method called.
You can try with some simple regular expression :
bool IsNumber(string text)
{
Regex regex = new Regex(#"^[-+]?[0-9]*\.?[0-9]+$");
return regex.IsMatch(text);
}
private void SetNumber(string n)
{
int nVal = 0;
if (int.TryParse(n, out nVal))
{
if (nVal < 0)
number = Math.Abs(nVal);
else
number = nVal;
}
else
number = 0;
}
There are a lot of problems with this code:
Using VB-style line comments (') instead of C# slashes
Parse for integer returns an int and not a bool
You should use TryParse with an out value
h does not seem to be valid at all. Is it a type for n?
There are variables that do not seem to be defined in function scope (number) are they defined at class scope?
But try this:
private void SetNumber(string n)
{
int myInt;
if (int.TryParse(n, out myInt)) //if user input is a number then
{
if (myInt < 0) //if user input is negative
number = Math.Abs(n); //assign absolute version of user input
else //else assign user input
number = n;
}
else number = 0; //if user input is not an int then set number to 0
}
You could try something like below using int.TryParse..
private void SetNumber(string n)
{
int parsed = -1;
if (int.TryParse(n, out parsed)) //if user input is a number then
...
The reason there are complaints that it cannot convert an int to a bool is because the return type of int.Parse() is an int and not a bool and in c# conditionals need to evaluate bool values.
int.Parse will give you back an integer rather than a boolean.
You could use int.TryParse as you suggested.
int parsedValue;
if(int.TryParse(n, out parsedValue))
{
}
Well for one thing the inner if statement has an 'h' instead of an 'n' if(h < 0). But TryParse should work there assuming that 'number' is a class variable.
private void SetNumber(string n)
{
int temp;
bool success = Int32.TryParse(n, out temp);
// If conversion successful
if (success)
{
// If user input is negative
if (temp < 0)
number = Math.Abs(temp); // Assign absolute version of user input
else // Assign user input
number = temp;
}
else
{
number = 0;
}
}
int.Parse will convert a string to an integer. Current you have it within an if statement, so its treating the returned value of int.Parse as a bool, which its not.
Something like this will work:
private void SetNumber(string n)
{
int num = 0;
try{
num = int.Parse(n);
number = Math.Abs(num);
}catch(Exception e){
number = 0;
}
}
I did this in the simplest way I knew how.
static void Main(string[] args)
{
string a, b;
int f1, f2, x, y;
Console.WriteLine("Enter two inputs");
a = Convert.ToString(Console.ReadLine());
b = Console.ReadLine();
f1 = find(a);
f2 = find(b);
if (f1 == 0 && f2 == 0)
{
x = Convert.ToInt32(a);
y = Convert.ToInt32(b);
Console.WriteLine("Two inputs r number \n so tha additon of these text box is= " + (x + y).ToString());
}
else
Console.WriteLine("One or tho inputs r string \n so tha concadination of these text box is = " + (a + b));
Console.ReadKey();
}
static int find(string s)
{
string s1 = "";
int f;
for (int i = 0; i < s.Length; i++)
for (int j = 0; j <= 9; j++)
{
string c = j.ToString();
if (c[0] == s[i])
{
s1 += c[0];
}
}
if (s==s1)
f= 0;
else
f= 1;
return f;
}

A function to return a sign

I know this will really turn out to be simple, but my brain is just not working. I need a function in C# that will return -1 if the integer passed to the function has a negative sign, return 1 if the integer has a positive sign and return 0 if the number passed is 0. So for example:
int Sign=SignFunction(-82); // Should return -1
int Sign2=SignFunction(197); // Should return 1
int Sign3=SignFunction(0); // Should return 0
This is already in the framework. Just use Math.Sign...
int sign = Math.Sign(-82); // Should return -1
int sign2 = Math.Sign(197); // Should return 1
int sign3 = Math.Sign(0); // Should return 0
In addition, it will work with:
int sign4 = Math.Sign(-5.2); // Double value, returns -1
int sign5 = Math.Sign(0.0m); // Decimal, returns 0
// ....
int sign = Math.Sign(number);
It already exists.
public int SignFunction(int number)
{
return number.CompareTo(0);
}
public int SignFunction( int input )
{
if( input < 0 ) return -1;
if( input > 0 ) return 1;
return 0;
}
return input.CompareTo(0);
public int SignFunction(int number) {
return (number > 0) ?
1 : (number < 0) ?
-1 : number;
}
If Math.Sign did not exist, I would do this:
return x == 0 ? 0 : x / Math.Abs(x);
public int Sign(int number)
{
if(number==0)
return 0;
return number/Math.Abs(number);
}

In C# should try-catch be used for is-numeric testing?

I have heard that using exception trapping is not a recommended practice for number testing.
For example:
bool isnumeric
try
{
int i = int.parse(textbox1.text);
isnumeric = true;
}
catch {isnumenric=false}
Is there some other way that I could test for numbers in C#?
Yes try using
int i;
bool success = Int32.TryParse(textBox1.text, out i);
The TryParse method basically does what you are doing above.
Use the built-in TryParse
E.g.
int number;
bool result = Int32.TryParse(value, out number);
Yes. Use int.TryParse, double.TryParse, etc. instead, which all return a boolean.
Alternately, there's an IsNumeric function buried in the VB assemblies (in the Microsoft.VisualBasic namespace in Microsoft.VisualBasic.dll) that you can also call from your C# code:
bool Microsoft.VisualBasic.Information.IsNumeric(value)
TryParse()
int i;
if(Int32.TryParse(someString,out i))
{
//now use i because you know it is valid
//otherwise, TryParse would have returned false
}
int result = -1;
bool isNumeric = Int32.TryParse(text, out result);
isNumeric will be true if the number is numeric, false otherwise; if the number is numeric, result will have the numeric value of the number.
bool TryParse(string, out int)
It will return a bool that is true if it was able to parse the integer, and the out parameter will contain the integer (if it was successful with the parsing).
If you just need to do number testing and do not need the integer number, you may use the function below. This is faster than Int32.TryParse(...) methods.
Edit for Barry Fandango: Handles negative numbers now. This is only for testing integers.
public static bool IsNumber(string s)
{
if (s == null || s.Length == 0)
{
return false;
}
if (s[0] == '-')
{
for (int i = 1; i < s.Length; i++)
{
if (!char.IsDigit(s[i]))
{
return false;
}
}
}
else
{
foreach (char c in s)
{
if (!char.IsDigit(c))
{
return false;
}
}
}
return true;
}
If you want the integer then Int32.TryParse(...) is what you want else
Information.IsNumeric(...) (From the Microsoft.VisualBasic.dll) if you don't care what the actual integer is.

Categories

Resources