convert to double 5.55111512312578E-17 - c#

How to convert -5.55111512312578E-17 to 5.55?
my code:
var value=reader11["PendingQty"].ToString().Replace('-', ' ');
var a=String.Format("{0:0.00}", value);
i also Tried : value= Math.round

-5.55111512312578E-17 is equal to 0.0000000000000000555111512312578. You could get this value by doing this:
double output = Double.Parse(input, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(output.ToString("F99").TrimEnd('0'));
But as far as I understood, you actually only want to first three digits, so I would do a string manipulation:
input.Substring(1,4);
This takes 4 characters, starting at the second position. If you have positive values too, simply check and read from the first digit on:
var res = "";
if (input.StartsWith("-")) {
res = input.Substring(1,4));
}
else {
res = input.Substring(0,4);
}

Related

Extracting double value from a string c#

I want to extract the double from my string.
buff = "VA VV_CELL1 3.55"
When i use the following code
private void GetLine(string msg, string buff, double numb)
{
comPort.WriteLine(msg);
Thread.Sleep(50);
buff = comPort.ReadExisting();
Thread.Sleep(50);
MatchCollection matches = Regex.Matches(buff, #".*?([-]{0,1} *\d+.\d+)");
List<double> doubles = new List<double>();
foreach (Match match in matches)
{
string value = match.Groups[1].Value;
value = value.Replace(" ", "");
doubles.Add(double.Parse(value));
Thread.Sleep(200);
numb = doubles[0];
}
}
This code work for my other strings but "CELL1" contains a number so i dont get the wanted value "3.55" any ideas?
Why you don't simply split this string and take the last part?
string numberPart = buff.Split().Last();
double num;
bool validNum = double.TryParse(numberPart, NumberStyles.Any, CultureInfo.InvariantCulture, out num);
Another way is to use Substring and LastIndexOf(which fails if there is no space):
string numberPart = buff.Substring(buff.LastIndexOf(' ')).Trim();
To help on your comment:
I'd use a method that returns a double?(double that can be null):
double? GetNumber(string buff)
{
string numberPart = buff.Split().Last();
double num;
bool validNum = double.TryParse(numberPart, NumberStyles.Any, CultureInfo.InvariantCulture, out num);
if (validNum)
return num;
else
return null;
}
Now you can use the method and you even know whether the number could be parsed successfully or not:
double? result = GetNumber("VA VV_CELL1");
bool wasValid = result.HasValue;
if(wasValid)
{
double value = result.Value;
}
Try, this regex expression : \s+\d+(.)?\d+
I assume you want to capture both doubles and integers, otherwise you could write \d+\.\d+. This :
Regex.Matches("VA VV_CELL1 3.55",#"\d+\.\d+")[0]
Returns 3.55 but can't capture 355.
You can capture an integer or decimal preceded by whitespace with \s+\d+(\.\d+)?.
Regex.Matches("VA VV_CELL1 3.55",#"\s+\d+(\.\d+)?")[0]
Returns 3.55 while
Regex.Matches("VA VV_CELL1 355",#"\s+\d+(\.\d+)?")[0]
Returns 355
If you want to capture only the last field you can use \s+\d+(\.\d+)?$,eg:
Regex.Matches("VA VV_CELL1 3.54 3.55",#"\s+\d+(\.\d+)?$")[0]
Returns 3.55
You don't need to trim whitespace because double.Parse ignores it. You can change the pattern to capture the number in a separate group though, by surrounding the digits with parentheses :
Regex.Matches("VA VV_CELL1 3.54 3.55",#"\s+(\d+(\.\d+)?)$")[0].Groups[1]
You need to use Groups[1] because the first group always returns the entire capture

double.ToString(???) - format to drop digits BEFORE decimal point and show 2 digits AFTER decimal point?

Is it possible to dislay only the cents in an amount using only ToString(), something like 1.99.ToString("SOME FORMAT HERE")?
e.g. what if I want 1.99 to be displayed as "1 dollar(s) 99 cents"
($"{ Convert.ToInt32(amount) } dollar(s) { amount.ToString("???") } cents")?
This would work if amount is a double. If amount is string then you wouldn't need ToString() in following line. Note this is assuming a format you listed in your question:
string line = string.Concat("$", amount.ToString().Split('.')[0], " dollar(s) ", amount.ToString().Split('.')[1].Substring(0,2), " cents");
I don't think you will be able to do this with only the ToString method, so here's another way.
You can first get the decimal part by doing this:
var decimalPart = yourDouble - (int)yourDouble;
Then, you can times the decimal part by 100 and convert the result to an int.
var twoDigits = (int)(decimalPart * 100);
To convert this to a two digit string, you just pad 0s to the left:
var result = twoDigits.ToString().PadLeft(2, '0');
I can not do this using only ToString(), but this is almost what you want :)
double d = 15.12;
var str = d.ToString("0 dollar(s) .00 cents").Replace(".", string.Empty);
Anyway, I suggest you to create an extension method to do this:
public static class Extensions
{
public static string ToFormattedString(this double number)
{
var integerPart = Convert.ToInt32(number);
var decimalPart = Convert.ToInt32((number - integerPart) * 100);
return String.Format("{0} dollar(s) {1} cents", integerPart, decimalPart);
}
}
usage:
Console.WriteLine(d.ToFormattedString());

Get exponential value using regular expression

I have string like this:
strings s = "1.0E-20"
Is there a way to get only -20 from this using regex?
I tried this:
(([1-9]+\.[0-9]*)|([1-9]*\.[0-9]+)|([1-9]+))([eE][-+]?[0-9]+)?
this gets me e-20 in group5 but still not just -20.
Use Regex for dealing with text, use Math(s) for dealing with numbers:
Math.Log10(Convert.ToDouble("1.0E-20")) // returns -20
To make sure your string input is a valid double use TryParse:
double d, result = 0.0;
if (Double.TryParse("1.0E-20", out d))
{
result = Math.Log10(d);
}
else
{
// handle error
}
Also, if you want to get the 1.0 (multiplier) from your input:
var d = Convert.ToDouble("1.0E-20");
var exponent = Math.Log10(d);
var multiplier = d / exponent;
No need for Regex when string methods can do wonders
string str = "1.0E-20";
str = str.Substring(str.IndexOf('E') + 1);
You can do that without Regex like:
string s = "1.0E-20";
string newStr = s.Substring(s.IndexOf('E') + 1);
Later you can parse the string to number like:
int number;
if (!int.TryParse(newStr, out number))
{
//invalid number
}
Console.WriteLine(number);
You can also use string.Split like:
string numberString = s.Split('E')[1]; //gives "-20"
Its better if you add check for string/array length when access string.Substring or accessing element 1 after split.
var x = str.IndexOf("E") != -1 ? str.Substring(str.IndexOf("E") + 1) : "1";
If you want to use regular expressions to achieve this, you should switch up your capture groups.
(([1-9]+\.[0-9]*)|([1-9]*\.[0-9]+)|([1-9]+))([eE])([-+]?[0-9]+)?
Group 6 will contain -20 with your given example with the regular expression above. Note how the parentheses have moved. We might need more information from you though. Do you have any more sample data? What's the end goal here?

Parse string and return only the information between bracket symbols. C# Winforms

I would like to parse a string to return only a value that is in between bracket symbols, such as [10.2%]. Then I would need to strip the "%" symbol and convert the decimal to a rounded up/down integer. So, [10.2%] would end up being 10. And, [11.8%] would end up being 12.
Hopefully I have provided sufficient information.
Math.Round(
double.Parse(
"[11.8%]".Split(new [] {"[", "]", "%"},
StringSplitOptions.RemoveEmptyEntries)[0]))
Why not use Regex?
In this example, I am assuming that your value inside the brackets always are a double with decimals.
string WithBrackets = "[11.8%]";
string AsDouble = Regex.Match(WithBrackets, "\d{1,9}\.\d{1,9}").value;
int Out = Math.Round(Convert.ToDouble(AsDouble.replace(".", ","));
var s = "[10.2%]";
var numberString = s.Split(new char[] {'[',']','%'},StringSplitOptions.RemoveEmptyEntries).First();
var number = Math.Round(Covnert.ToDouble(numberString));
If you can ensure that the content between the brackets is of the form <decimal>%, then this little function will return the value between the fist set of brackets. If there are more than one values you need to extract then you will need to modify it somewhat.
public decimal getProp(string str)
{
int obIndex = str.IndexOf("["); // get the index of the open bracket
int cbIndex = str.IndexOf("]"); // get the index of the close bracket
decimal d = decimal.Parse(str.Substring(obIndex + 1, cbIndex - obIndex - 2)); // this extracts the numerical part and converts it to a decimal (assumes a % before the ])
return Math.Round(d); // return the number rounded to the nearest integer
}
For example getProp("I like cookies [66.7%]") gives the Decimal number 67
Use regular expressions (Regex) to find the required words within one bracket.
This is the code you need:
Use an foreach loop to remove the % and convert to int.
List<int> myValues = new List<int>();
foreach(string s in Regex.Match(MYTEXT, #"\[(?<tag>[^\]]*)\]")){
s = s.TrimEnd('%');
myValues.Add(Math.Round(Convert.ToDouble(s)));
}

Double to string -- formatter missed?

I have to convert a double to string with the following rules:
If decimal point position is -1 (or another non-existing value meaning 'Auto'), fractional part of the number should be output with all significant digits (all zeroes at the end should be trimmed). If the double is integer, its fractional part shouldn't output at all. For instance, digits = -1: 1029.0 -> 1,029, 1029.123456789 -> 1,029.123456789.
If decimal point position is equal or greater than 0, fractional part of the number should be output with the given number of digits. For instance, digits = 2: 1029.0 -> 1,029.00, 1029.123456789 -> 1,029.12.
Conversion should be culture-dependant (point or comma as decimal point, comma or space as group divider etc).
I have a code for the task:
var _Culture = CultureInfo.CreateSpecificCulture("en-US");
object sourceValue = 1029.0;//.123456789;
int digits = -1; // 2;
var formatter = "G";
if (digits != -1)
{
_Culture.NumberFormat.NumberDecimalDigits = digits;
formatter = "N";
}
var sourceValueAsFloat = (double)sourceValue;
var s = sourceValueAsFloat.ToString(formatter, _Culture);
Is there another formatter (not "N" or "G"), I can use instead? Or, maybe, I can use "N"/"G" another way?
Regards,
See here and here for all the format string specifiers .net understands.
// preferably make allDigits a static field to avoid re-allocating on every call
string allDigits = "#,0." + new string('#', 350);
string output = sourceValue.ToString(
digits < 0 ? allDigits : "#,0." + new string('0', digits));
And if you need to handle different cultures explicitly:
string output = sourceValue.ToString(
digits < 0 ? allDigits : "#,0." + new string('0', digits),
culture);

Categories