Link to home
Start Free TrialLog in
Avatar of chudmarek
chudmarek

asked on

Double.Parse C#

Hi Guys,

Hopefully an easy one.


I'm parsing two strings and converting them to doubles using double.Parse .

For example,

string1 = 2.32;
string2 = 2.37.

So i use if( double.Parse(string2) > double.Parse(string1)
{
//do something
}

The problem occurs, very rarely, that it will still go into "do something" even if string2 is not greater than string1. My values usually aren't so close....by that i mean that string1 and string2 values could be a lot further apart. So i'm wondering if there is any way that the double.Parse is rounding anything off, so when the values are too close like in the example above the statement holds true.

Thanks.


ASKER CERTIFIED SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of chudmarek
chudmarek

ASKER

Hi,

I thought that double should stay as the exact number...it is just strange.

Jandromeda, I can't give two values because the values are always changing and no two values are ever the same.

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
as I know, there no function u want,
so u'll write it by yourself,
It's may help u,

private void button2_Click(object sender, EventArgs e)
{
	string string1 = "2.32";
	string string2 = "2.37";
 
	double d1 = double.Parse("2.321");
	double d2 = double.Parse("2.376");
 
	d1 = Truncate(d1, 2);
	d2 = Truncate(d2, 2);
 
	if (d2 > d1)
	{
		// Do
	}
}
 
private double Truncate(double val, int de)
{
	double dval = val*(Math.Pow(10,de));
 
	dval = Math.Round(dval);
 
	return dval / Math.Pow(10, de);
}

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial