Converting Double to String with multiple format specifiers - c#

I'm trying to convert a Double to String, I need both round-tripping R and lowercase exponential notation enabled. I've looked at NumberFormatInfo, but it doesn't seem to define the exponent symbol.
I'm aware of x.ToString("R").ToLower(), but I prefer a direct approach if there is any.
The references I've examined:
https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx

double value = 12345.6789;
//Roundtrip
Console.WriteLine(value.ToString("R")); // Result: 12345.6789
//Lowercase "e" denotes lowercase exponent symbol
Console.WriteLine(value.ToString("e")); // Result: 1.234568e+004
//Likewise uppercase "E" denotes uppercase exponent symbol
Console.WriteLine(value.ToString("E")); // Result: 1.234568E+004
//add precision after the "e"
Console.WriteLine(value.ToString("e8")); // Result: 1.23456789e+004
//Variable Precision
int Precision = value.ToString("R").Replace(".", "").Length - 1;
Console.WriteLine(value.ToString("e" + Precision.ToString())); //Result: 1.23456789e+004
https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx#EFormatString

Related

C# byte array calculation with BigInteger not working properly

So, i need to calculate byte arrays in my program and i noticed weird thing:
string aaa = "F8F9FAFBFCFD";
string aaaah = "10101010101";
BigInteger dsa = BigInteger.Parse(aaa, NumberStyles.HexNumber) + BigInteger.Parse(aaaah, NumberStyles.HexNumber);
MessageBox.Show(dsa.ToString("X"));
When i add aaa + aaah, it displays me 9FAFBFCFDFE, but it should display F9FAFBFCFDFE, but when i subtract it does it right, aaa - aaah, displays F7F8F9FAFBFC, everything should be right in my code.
BigInteger.Parse interprets "F8F9FAFBFCFD" as the negative number -7,722,435,347,203 (using two's complement) and not 273,752,541,363,453 as you were probably expecting.
From the documentation for BigInteger.Parse:
If value is a hexadecimal string, the Parse(String, NumberStyles)
method interprets value as a negative number stored by using two's
complement representation if its first two hexadecimal digits are
greater than or equal to 0x80. In other words, the method interprets
the highest-order bit of the first byte in value as the sign bit.
To get the result you are expecting, prefix aaa with a 0 to force it to be interpreted as a positive value:
string aaa = "0F8F9FAFBFCFD";
string aaaah = "10101010101";
BigInteger dsa = BigInteger.Parse(aaa, NumberStyles.HexNumber)
+ BigInteger.Parse(aaaah, NumberStyles.HexNumber);
MessageBox.Show(dsa.ToString("X")); // outputs 0F9FAFBFCFDFE

Show double as percentage without decimals with ToString method

Looking for:
95,4545454545455 -> 95 %
I tried using:
String resultAsPercentage = result.ToString("##0 %");
But, it shows
9545 %
Then, I solved my problem using regex:
Question: Why my ToString method hasn't worked? And how to fix it to avoid using regex?
Thanks in advance.
As documented on Custom Numeric Format Strings, the % modifier multiplies the value by 100 before inserting the %. It's intended to be used with fractions. To disable this special meaning of %, escape it by preceding it with #"\".
Alternatively, you could take the % out of the format string, and append it manually: result.ToString("##0") + " %".
If you don't care about rounding, you can use the following:
double result = 95.4545454545;
String resultAsPercentage = (int)result + " %";
System.out.println(resultAsPercentage);
Output is: 95 %
Casting to an int drops the decimal places without rounding
You can use thew P(ercentage) format specifier, you need to divide through 100 because the specifier multiplies it by 100:
decimal value = 95.4545454545455m;
String resultAsPercentage = (value / 100).ToString("P0"); // 95%
If you need the space between the value and the percentage symbol you could use this approach:
NumberFormatInfo nfi = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
nfi.PercentSymbol = " %";
String resultAsPercentage = (value / 100).ToString("P0", nfi); // 95 %
One way can be Clone a culture (like InvariantCulture), set it's PercentPositivePattern to 0, divide your value by 100 and get it's string representation using The percent ("P") format specifier with 0 precision and that cloned culture as;
var clone = (CultureInfo)CultureInfo.InvariantCulture.Clone();
clone.NumberFormat.PercentNegativePattern = 0;
Console.WriteLine(((int)95.4545454545455 / 100.0).ToString("P0", clone)); // 95 %
You can see all associated patterns on Remarks section on that page.
You can guaranteed to set PercentNegativePattern property as well for negative values.

using Regular Expression how to get (16.00 + 28.66 = 44.66) as 44.66 and (99) as 99

Im using regular expression to get values such as (16.00 + 28.66 = 44.66) as 44.66 ,(26.00) as 26.00
I have trouble to display data when its just(99) as 99 without any decimal.
I have used the below code to till now
string amount = DropDownList1.SelectedItem.Text;
Regex regex = new Regex("(\\d+\\.\\d{2})(?=\\))", RegexOptions.Multiline | RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
Someone please tell me how can i display a value without any decimal..
Eg-(99) as 99
Does your drop down list contain values like these?
(20.01 + 20.01 = 40.02)
(40.02)
(40)
If yes, you can try this Regular Expression
(\\d+(\\.\\d{2})?)(?=\\))
You can do it without Regex using ToString format, you can fix the number of decimal places. The 99 will be 99.00. You can read more about custom numeric formats over here.
string formatedNum = double.Parse(DropDownList1.SelectedItem.Text).ToString(".00");
The "0" custom format specifier serves as a zero-placeholder symbol.
If the value that is being formatted has a digit in the position where
the zero appears in the format string, that digit is copied to the
result string; otherwise, a zero appears in the result string. The
position of the leftmost zero before the decimal point and the
rightmost zero after the decimal point determines the range of digits
that are always present in the result string, MSDN.

Math.Floor Behaviour

double c, d, e;
double a = (c - d) / e;
double b = Math.Floor(a);
Debug.WriteLine(a.ToString() + " " + b.ToString());
Code above outputs "3 2" at one configuration where all numbers are double. How is this possible? Is it because of fractional error resulting from double operations? However I think a.ToString() should give the whole number with its fractional part.
It's just a matter of what double.ToString() does. Here's a short but complete program demonstrating the same thing:
using System;
public class Test
{
static void Main(string[] args)
{
// Find the largest double less than 3
long bits = BitConverter.DoubleToInt64Bits(3);
double a = BitConverter.Int64BitsToDouble(bits - 1);
double b = Math.Floor(a);
// Print them using the default conversion to string...
Console.WriteLine(a.ToString() + " " + b.ToString());
// Now use round-trip formatting...
Console.WriteLine(a.ToString("r") + " " + b.ToString("r"));
}
}
Output:
3 2
2.9999999999999996 2
Now double.ToString() is documented with:
This version of the ToString method implicitly uses the general numeric format specifier ("G") and the NumberFormatInfo for the current culture.
... and the general numeric format specifier docs state:
The precision specifier defines the maximum number of significant digits that can appear in the result string. If the precision specifier is omitted or zero, the type of the number determines the default precision, as indicated in the following table.
... where the table shows that the default precision for double is 15. If you consider 2.9999999999999996 rounded to 15 significant digits, you end up with 3.
In fact, the exact value of a here is:
2.999999999999999555910790149937383830547332763671875
... which again, is 3 when regarded with 15 significant digits.

Math.Round not keeping the trailing zero

I need all values to rounded to two decimal places. So 1.401 should round to 1.40, but Math.Round(value, 2) rounds to 1.4.
How can I force the trailing zero?
1.4 is the same as 1.40 - you just want to display it differently. Use a format string when calling ToString - like value.ToString("0.00")
1.4 == 1.40 the only time you'd ever need a trailing 0 is when you display the number..i.e. format it to string.
.ToString("N2");
The trailing zero is more of a formatting than a value issue, so use
foo.ToString("0.00")
I know this is an old question, but might help someone!
I am using a c# xml class to populate and then serialise to xml. One of the values is a double. If I assign a '7' to the value this gets serialised to '7' when I actually need '7.00'. Easiest way round this was just to do:
foo = doubleValue + 0.00M
And that makes the value 7.00 instead of just 7. Thought this was better then doing a ToString and then parsing it back.
The trailing zero is just a presentation. Math-wise, 1.40 and 1.4 are equivalent.
Use formatting instead to present it with the 2 decimal places:
String.Format("{0:0.00}", 1.4);
or
yourNumber.ToString("0.00");
It has to do with whether you use a decimal or a double.
While internally (as it appears from the Source Code) Math.Round() preserves the trailing zeros even on a double, still the fact that it is saved as a double in memory causes automatically to remove all trailing zeros
So if you do want tailing zeros, you can either use the string display functions to format it as others have answered, or make sure to pass in the original value as a decimal (causing to use internally Decimal.Math.Round which will deal only with decimals), and make sure to not cast the result to a double and also not to save it in a double variable.
Similarly if you have a decimal and you don't want trailing zeros, just cast it to a double (you can either cast the input to Math.Round or the result, it doesn't matter as long as somewhere in the way it is becoming a double).
It is a number (double?), so it doesn't have a trailing zero - you have to make it text and force a trailing zero.
You can use this function instead of round and just use it like you use round function.
import decimal
def printf(x, n):
d = decimal.Decimal(str(x))
d0 = -(d.as_tuple().exponent)
if d0 < n:
print("x = ", x)
else:
d1 = decimal.Decimal(str(round(x, n)))
d2 = d1.as_tuple().exponent
MAX = n + d2
if MAX == 0:
print("x = ", round(x, n))
else:
i = 0
print("x = ", round(x, n), end = '')
while i != MAX:
if i == (MAX - 1):
print("0")
else:
print("0", end = '')
i = i + 1
So you must have something like this.
>>> printf(0.500000000000001, 13)
>>> 0.5000000000000

Categories

Resources