BigInteger.ToString in scientific notation (i.e. with E) - c#

Double.ToString on a very large number usually returns only a number of significant digits, followed by the exponent notation with a power of ten. However, BigInteger doesn't do this, and simply returns all digits of the number.
How can I tell it to output only in the scientific format like double does instead of the full number? I can't convert it to double, because it is greater than Double.MaxValue. I could build a formatting function myself, but I would be happier if there was a built-in feature taking all cultures into account.

Like most ToString methods, BigInteger.ToString allows you to pass a format string:
var myString = myBigInteger.ToString("E"); // yields exponential notation
See the following MSDN page for a detailed description of the built-in numeric format strings available in .NET:
Standard Numeric Format Strings
Note that the Exponential Format Specifier allows you to provide an optional precision specifier.

You should simply be able to use the BigInteger.ToString() method along with the expected Exponential formatting string E to handle scientific notation :
var input = BigInteger.Parse("12498124912841982142441242424421");
var output = input.ToString("E"); // yields "1.249812E+031"

Related

What format is used for xml-serialization of numbers in C#?

When I write:
var d = 12.34D;
d.ToString();
it gives "12,34", but when I serialize object with double field, it gives "12.34"
It is because XmlSerializer uses some specific format/culture? What exactly? I've looked into Double's source code but not seen implementation of IXmlSerializable.
Thanks.
The XmlSerializerWriter uses XmlConvert.ToString to convert the values.
The relevant part from that class is this:
return value.ToString("R", NumberFormatInfo.InvariantInfo);
So it uses the invariant culture, which happens to output the string that is conforming to the XML RFC (So a period as decimal separator).
Format specifier "R" is documented here:
The round-trip ("R") format specifier attempts to ensure that a numeric value that is converted to a string is parsed back into the same numeric value. This format is supported only for the Single, Double, and BigInteger types.
It means that the other end will produce the same double result when deserializing the string value.

How to deal with right zeros in a string to decimal conversion?

in my website i need to read data from a XML, and some of these datas are decimal values.
Sometimes the value comes correct: 1 or 72,59and sometimes the value comes like 1.0000 or 72,590000, how is the best way to convert it to the right format:
ps: I need a string value.
Thanks!
What format are you wanting them to go to, specifically? How many decimals, etc?
If you want always 2 decimals, try a standard numeric formatting such as:
decimal value = 123.456;
Console.WriteLine("Your account balance is {0:F}.", value);
See this MSDN example for other common numeric formatting techniques.
You write that you tried
string.Format("{0:F}","1.00000");
The problem with this is that you're passing a string into the function. Numeric formatting only works on numeric data types. Convert the value to a decimal first and then format it.
Try this
public string ReformatDecimalString(string input)
{
const string formatString = //something
var decimalValue = decimal.Parse(input);
return decimalValue.ToString(formatString);
}
When you are formatting a single numeric value, it's slightly more efficient to use x.ToString(formatString) than string.Format(formatString, x). But note that the specific format string will be different in the two cases.
If your input data has decimal points (not commas) and your computer's culture uses decimal commas, you ought to be able to parse the value correctly by using CultureInfo.InvariantCulture:
var decimalValue = decimal.Parse(input, CultureInfo.InvariantCulture);
If I'm reading your answer correctly, you're trying to convert Integer values you pull from an XML file into string values without trailing zeroes ("ps: I need a string value.")
this code:
decimal test = 20.000000m
test.ToString("G29");
might do what you want

Math.Round, keep decimal place [duplicate]

This question already has answers here:
Formatting a float to 2 decimal places
(9 answers)
Closed 9 years ago.
For example.
Math.Round(2.314, 2) //2.31
Math.Round(2.301, 2) //2.3 , but I want this as 2.30
Numbers don't have any conception of zeroes after a decimal point.
You're actually asking how to convert the number into a string with extra zeroes:
(2.301).ToString("0.00") // "2.30"
See numeric format strings for more detail.
In particular, the 0 specifier will round away from zero.
You want a string formatting of the number:
string val = Math.Round(2.301, 2).ToString("F2");
here's a post on formatting numbers in C#
2.3 and 2.30 are the same thing. If you want the string 2.30 then use .ToString("F2") on the Math.Round function.
2.3 and 2.30 is the same thing from a code perspective. You can display the trailing zero by formatting a string:
string yourString = Math.Round(2.301, 3).ToString("0.00");
The decimal is still there, you're probably just not seeing because when you look at the string representation, by default it will omit trailing zeros. You can overwrite this behavior by passing a format string to ToString():
Console.WriteLine(Math.Round(2.301, 2).ToString("N2")) // 2.30
But of course, if this is just for display purposes, you don't really need to call Math.Round:
Console.WriteLine(2.301.ToString("N2")) // 2.30
Further Reading
Standard Numeric Format Strings
Custom Numeric Format Strings
If you use decimal numbers (their literals end with m, for "money"), you get the behavior you're after. double numbers don't have a concept of significant zeroes the same way that decimals do.
Math.Round(2.314m, 2);
Math.Round(2.301m, 2);
Or if you want to change how you see the numbers, you can use a string format:
Math.Round(2.314, 2).ToString("N2");
Math.Round(2.301, 2).ToString("N2");

Use scientific notation only if needed

I want to parse a double value into a string. I want my number to have a specified number of digits (that I won't know until runtime). If this number can be expressed with a non-zero value in number of digits this is what I want. If the number comes out as zero's like this I want it expressed in scientific notation.
Some examples will make this more clear, this assumes I wanted 3 digits:
Value: .2367 Output: "0.23"
Value: .00367 Output: "3.67E-3"
Value: 22.3 Output: "22.3"
Value: 3364.0 Output: "3.36E3"
My work around solution would use the ToString() method and the N numeric format string and if it results in zero's revert to the E format string, but this feels like reinventing the wheel. Does anyone know if a built in method to do this?
Have you looked at using the General Number Format Specifier?
The general ("G") format specifier converts a number to the most
compact of either fixed-point or scientific notation, depending on the
type of the number and whether a precision specifier is present.
Some samples from the documentation:
double number;
number = .0023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 0.0023
number = 1234;
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));
// Displays 1.2E+03
number = Math.PI;
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));
// Displays 3.1416

Can't parse text to Decimal

In Form_load I have
txtAlteFonduri.Text = "5,00";
txtFReparatii.Text = "15,00";
txtFRulment.Text = "20,00";
and in another function I want to parse text as decimal
decimal alteFonduri = Decimal.Parse(txtAlteFonduri.Text);
decimal fondRulment = Decimal.Parse(txtFRulment.Text);
decimal fondRepar = Decimal.Parse(txtFReparatii.Text);
but I have an error in the second line
Input string was not in a correct format.
You need to specifically add the number format. For your examples above, the following should work:
decimal alteFonduri = Decimal.Parse(txtAlteFonduri.Text, CultureInfo.GetCulture("de-DE"));
Otherwise, the system's culture information is used.
You are using a different culture to what decimal.Parse() is expecting (it expects the decimal point '.' but you provide a comma. Using the correct culture should correctly parse the strings, although I can run your code without having any errors...
You can use Decimal.Parse(variable, CultureInfo.GetCultureInfo("Culture-Name"));
You have to use this overload of Decimal.Parse and supply a IFormatProvider matching the culture of your input. You should also consider using one of the Decimal.TryParse methods for better error handling.

Categories