I need to make sure that a double always ends with 0
6 = 6.0
5.9876577878 = 5.98765778780
I tried the format but did not bring the expected result.
How can this be done?
Not sure if the String.Format method allows you to do this. Here's something you can do though:
public static class DoubleUtils {
public static String EnsureEndsWithZero(this double value) {
String str = value.ToString();
if(!str.EndsWith("0")) {
if(str.Contains(".")) {
str += "0";
} else {
str += ".0";
}
}
return str;
}
}
Usage:
double val = 10.1;
Console.WriteLine(val.EnsureEndsWithZero());
Unless you're extremely liberal about how many zeros are at the end of the number (i.e. 1 OR MORE zeros is okay), then I think you'd have to check the resulting string to see if there's a zero after the decimal point, and add one or both if they aren't there.
Related
public bool VerifyTextPresent(By by, String actual)
{
WaitUntilElementIsPresent(by);
String expected = GetText(by);
return expected.Equals(actual);
}
expected = "Total Win"
actual = "Total Win"
I used "Contains" method also but return false only.
Please help me out on this.
I got the thing like i ptrinted its ascii value and for actual space value is 160 and for expected space value is 32. But now how can i now move ahead??
One approach is to normalize your strings by replacing certain characters with a baseline. In your case you can replace non-breaking spaces with a "normal" space:
public bool VerifyTextPresent(By by, String actual)
{
WaitUntilElementIsPresent(by);
String expected = GetText(by);
if (expected.Equals(actual)) return true;
if (expected.Equals(Normalize(actual))) return true;
return false;
}
private string Normalize(string s)
{
// hard-code for now; could use a lookup table or other means to expand
s = s.Replace((char)160, (char)32);
// other replacements as necessary
return s;
}
I have a long string with double-type values separated by # -value1#value2#value3# etc
I splitted it to string table. Then, I want to convert every single element from this table to double type and I get an error. What is wrong with type-conversion here?
string a = "52.8725945#18.69872650000002#50.9028073#14.971600200000012#51.260062#15.5859949000000662452.23862099999999#19.372202799999250800000045#51.7808372#19.474096499999973#";
string[] someArray = a.Split(new char[] { '#' });
for (int i = 0; i < someArray.Length; i++)
{
Console.WriteLine(someArray[i]); // correct value
Convert.ToDouble(someArray[i]); // error
}
There are 3 problems.
1) Incorrect decimal separator
Different cultures use different decimal separators (namely , and .).
If you replace . with , it should work as expected:
Console.WriteLine(Convert.ToDouble("52,8725945"));
You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture (What is the invariant culture) e.g. using double.Parse:
double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);
You should also take a look at double.TryParse, you can use it with many options and it is especially useful to check wheter or not your string is a valid double.
2) You have an incorrect double
One of your values is incorrect, because it contains two dots:
15.5859949000000662452.23862099999999
3) Your array has an empty value at the end, which is an incorrect double
You can use overloaded Split which removes empty values:
string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
Add a class as Public and use it very easily like convertToInt32()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for Common
/// </summary>
public static class Common
{
public static double ConvertToDouble(string Value) {
if (Value == null) {
return 0;
}
else {
double OutVal;
double.TryParse(Value, out OutVal);
if (double.IsNaN(OutVal) || double.IsInfinity(OutVal)) {
return 0;
}
return OutVal;
}
}
}
Then Call The Function
double DirectExpense = Common.ConvertToDouble(dr["DrAmount"].ToString());
Most people already tried to answer your questions.
If you are still debugging, have you thought about using:
Double.TryParse(String, Double);
This will help you in determining what is wrong in each of the string first before you do the actual parsing.
If you have a culture-related problem, you might consider using:
Double.TryParse(String, NumberStyles, IFormatProvider, Double);
This http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx has a really good example on how to use them.
If you need a long, Int64.TryParse is also available: http://msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx
Hope that helps.
private double ConvertToDouble(string s)
{
char systemSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator[0];
double result = 0;
try
{
if (s != null)
if (!s.Contains(","))
result = double.Parse(s, CultureInfo.InvariantCulture);
else
result = Convert.ToDouble(s.Replace(".", systemSeparator.ToString()).Replace(",", systemSeparator.ToString()));
}
catch (Exception e)
{
try
{
result = Convert.ToDouble(s);
}
catch
{
try
{
result = Convert.ToDouble(s.Replace(",", ";").Replace(".", ",").Replace(";", "."));
}
catch {
throw new Exception("Wrong string-to-double format");
}
}
}
return result;
}
and successfully passed tests are:
Debug.Assert(ConvertToDouble("1.000.007") == 1000007.00);
Debug.Assert(ConvertToDouble("1.000.007,00") == 1000007.00);
Debug.Assert(ConvertToDouble("1.000,07") == 1000.07);
Debug.Assert(ConvertToDouble("1,000,007") == 1000007.00);
Debug.Assert(ConvertToDouble("1,000,000.07") == 1000000.07);
Debug.Assert(ConvertToDouble("1,007") == 1.007);
Debug.Assert(ConvertToDouble("1.07") == 1.07);
Debug.Assert(ConvertToDouble("1.007") == 1007.00);
Debug.Assert(ConvertToDouble("1.000.007E-08") == 0.07);
Debug.Assert(ConvertToDouble("1,000,007E-08") == 0.07);
In your string I see: 15.5859949000000662452.23862099999999 which is not a double (it has two decimal points). Perhaps it's just a legitimate input error?
You may also want to figure out if your last String will be empty, and account for that situation.
I have an old VB6 project that I am converting to C#. I have a string. I am verifying, 1 character at a time, that it only contains [E0-9.+-].
This is the old VB6 code:
sepIndex = 1
Do While Mid(xyString, sepIndex, 1) Like "[E0-9.+-]"
sepIndex = sepIndex + 1
Loop
I am then using the index number to calculate the Left of the same string, and convert it to a double. Using Right, I then cut the string down to the remaining part of the string that I want:
xFinal = CDbl(left(xyString, sepIndex - 1))
xyString = LTrim(right(xyString, Len(xyString) - sepIndex + 1))
This works great in VB, and I have no problems whatsoever. In C# it is different. Knowing that the only way to emulate Left/Mid/Right in C# is to create my own function, I did so (part of my Utils namespace):
public static string Mid(string param, int startIndex)
{
try
{
//start at the specified index and return all characters after it
//and assign it to a variable
string result = param.Substring(startIndex);
//return the result of the operation
return result;
}
catch
{
return string.Empty;
}
}
public static string Right(string param, int length)
{
try
{
//start at the index based on the lenght of the sting minus
//the specified lenght and assign it a variable
string result = param.Substring(param.Length - length, length);
//return the result of the operation
return result;
}
catch
{
return string.Empty;
}
}
public static string Left(string param, int length)
{
try
{
//we start at 0 since we want to get the characters starting from the
//left and with the specified lenght and assign it to a variable
string result = param.Substring(0, length);
//return the result of the operation
return result;
}
catch
{
return string.Empty;
}
}
To the best of my knowledge, I have converted the code from VB6 to C#. The problem is that when it finally sets xyString, it is cutting the string in the wrong spot, and still leaving a trailing character that I want in xFinal.
From what I gather, this may be either an index issue (which I know in C#, Substring is 0-based, so I changed sepIndex to the value of 0), or problem with the wrong loop structure.
Here is the converted code, and I hope I could get some idea of what is going on here:
sepIndex = 0;
while (Regex.IsMatch(Utils.Mid(xyString, sepIndex, 1), "[E0-9.+-]"))
{
sepIndex++;
}
xFinal = Convert.ToDouble(Utils.Left(xyString, sepIndex - 1)); // - 1
xyString = Utils.Right(xyString, xyString.Length - sepIndex + 1).TrimStart(' '); // + 1
EDIT
This has been solved. I simply removed the +1 and -1 from my Utils.Left function, and it returned the proper string. Thanks for the inputs.
Seems to be just RegEx math with negative condition - "[^E0-9.+-]":
var sepIndex = Regex.Match(xyString, #"[^E0-9\.+-]+").Index;
If you need to do it by hand the easiest way to get single character is to just get single character from the string without trimming:
// replace Utils.Mid(xyString, sepIndex, 1) with
xyString[sepIndex]
Try using following
do{
sepIndex++;
}while (Regex.IsMatch(Utils.Mid(xyString, sepIndex, 1), "[E0-9.+-]"))
why not importing microsoft.visualbasic namespace?
class Program
{
static void Main(string[] args)
{
string t = Microsoft.VisualBasic.Strings.Mid("hello", 2);
}
}
you can reuse what you had before
the following is my property where if we enter 45 then it appends 45.00 but then again it results in 45 because the value is converted from string. So what is the easiest way i can achieve this goal. Where if they enter 45 then it would result 45.00 in the value field;
public decimal Length
{
get { if (this is Detail)
return ((this as Detail).Length.ToString() == string.Empty)
? 0 : (this as Detail).Length; else return 0; }
set
{
if (this is Detail)
{
string val = string.Empty;
if (!value.ToString().Contains("."))
{
val = string.Format("{0}{1}", value.ToString(), ".00");
value =Math.Round(Convert.ToDecimal(val), 2);
}
else
value = Math.Round(value, 2);
(this as Detail).Length = (value.ToString().Trim() ==
string.Empty) ? 0 : value;
}
}
}
val = string.Format("{0:0.00}", value);
This has nothing to do with the property setter. You need to specify the string format in your GUI to round the numbers.
Also if (this is PersonalDetail) is a massive design flaw. Override the Length property in the PersonalDetail class instead. (not sure what the intent is with this property)
The problem is that 45m and 45.00m are the same thing, and since this is a decimal, it will always display "45" instead of "45.00" unless you use a string formatter every time you try to output it.
You could always make another property that does output what you want, such as:
public decimal Length { get; set; }
public string FormattedLength
{
get
{
return String.Format("{0:0.00}", this.Length);
}
}
On a side note I don't like this, but I believe it gets you more or less what you are looking for.
private int FindNumber(string sPar)
{
// Get the last number
int len = sPar.Length;
string s = sPar.Substring(len-1);
return new (int)Decimal(s);
}
In this I am getting the error ; required . Can any ine help me on this.
Thank You!
Change your code to this:
private int FindNumber(string sPar)
{
int len = sPar.Length;
string s = sPar.Substring(len - 1);
return Convert.ToInt32(s);
}
Or, even shorter:
private int FindNumber(string sPar)
{
return Convert.ToInt32(sPar.Substring(sPar.Length - 1));
}
I'm not 100% what you are trying to do here, but if you want to get 4 as the result from the string "17894" i guess you want to write it like this with minimum number of changes:
private int FindNumber(string sPar) {
// Get the last number
int len = sPar.Length;
string s = sPar.Substring(len-1);
return int.Parse(s);
}
No reason to include a decimal and parse it to an int if you are only taking one char of the string anyway.
Note that this will give an exception if the last char of the string for any reason is not a number.
what is Decimal(s)? If you mean "parse as a decimal, then cast to int":
return (int)decimal.Parse(s);
If it is known to be an integer, just:
return int.Parse(s);
Actually, since you are only interested in the last digit, you could cheat:
private static int FindNumber(string sPar)
{
char c = sPar[sPar.Length - 1];
if (c >= '0' && c <= '9') return (int)(c - '0');
throw new FormatException();
}
Decimal(s) is not a valid call since Decimal is a type. Try Decimal.Parse(s) instead if you are certain that s is a valid decimal, stored as a string. If not, use Decimal.TryParse instead.
Please take into account different Culture related problems also, check out the overload that takes an IFormatProvider (I think, not sure about the exact name)
Do you just want to parse the digit from the last position in the string?
private int FindNumber(string sPar)
{
return int.Parse(sPar.Substring(sPar.Length - 1));
}
Note that this will fail if (a) the string is null, (b) the string is empty, or (c) the last character of the string isn't a digit. You should add some checking to your method if these situations are likely to be a problem.
The last line is completely wrong.
Your code takes the last char of a string(that i presume is always a number) and cast it to an int.
Do the following
try{
return Int32.Parse(s);
}
catch(Exception e)
{
// manage conversion exception here
}
I suppose you want to convert string to decimal as your code is not very clear.
you can use
Decimal d1;
if(Decimal.TryParse(sPar,out d1))
{
return d1
}
else
{
return 0;
}