C#: Exponential Format Specifier - c#

I have a double number:
element.MaxAllowableConcLimitPpm = 0.077724795640326971;
I need to display it as
7.7725e-2
when I try to use it:
element.MaxAllowableConcLimitPpm.ToString("e4", CultureInfo.InvariantCulture)
it returns
7.7725e-002
How to say that mantissa should have one symbol instead of 3 ?
Format like this:
.ToString("0.0000e0")
returns
5.0000e2
instead of
5.0000e+2

You have to use a custom numeric format string - standard numeric format strings always have at least three digits in the exponent.
Example with a custom string:
using System;
public class Test
{
static void Main()
{
double value = 0.077724795640326971;
Console.WriteLine(value.ToString("0.0000e+0")); // 7.7725e-2
}
}
From the documentation for standard numeric format strings (emphasis mine):
The case of the format specifier indicates whether to prefix the exponent with an "E" or an "e". The exponent always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet this minimum, if required.

Related

ToString format for fixed length of output - mixture of decimal and integer

I'm writing some code to display a number for a report. The number can range from 1. something to thousands, so the amount of precision I need to display depends on the value.
I would like to be able to pass something in .ToString() which will give me at least 3 digits - a mixture of the integer part and the decimal part.
Ex:
1.2345 -> "1.23"
21.552 -> "21.5"
19232.12 -> "19232"
Using 000 as a format doesn't work, since it doesn't show any decimals, neither does 0.000 - which shows too many decimals when the whole part is larger than 10.
You could write an extension method for this:
public static string ToCustomString(this double d, int minDigits = 3)
{
// Get the number of digits of the integer part of the number.
int intDigits = (int)Math.Floor(Math.Log10(d) + 1);
// Calculate the decimal places to be used.
int decimalPlaces = Math.Max(0, minDigits - intDigits);
return d.ToString($"0.{new string('0', decimalPlaces)}");
}
Usage:
Console.WriteLine(1.2345.ToCustomString()); // 1.23
Console.WriteLine(21.552.ToCustomString()); // 21.6
Console.WriteLine(19232.12.ToCustomString()); // 19232
Console.WriteLine(1.2345.ToCustomString(minDigits:4)); // 1.235
Try it online.
I don't think this can be done with ToString() alone.
Instead, start by formatting the number with 2 trailing digits, then truncate as necessary:
static string FormatNumber3Digits(double n)
{
// format number with two trailing decimals
var numberString = n.ToString("0.00");
if(numberString.Length > 5)
// if resulting string is longer than 5 chars it means we have 3 or more digits occur before the decimal separator
numberString = numberString.Remove(numberString.Length - 3);
else if(numberString.Length == 5)
// if it's exactly 5 we just need to cut off the last digit to get NN.N
numberString = numberString.Remove(numberString.Length - 1);
return numberString;
}
Here's a regex, that will give you three digits of any number (if there's no decimal point, then all digits are matched):
#"^(?:\d\.\d{1,2}|\d{2}\.\d|[^.]+)"
Explanation:
^ match from start of string
either
\d\.\d{1,2} a digit followed by a dot followed by 1 or 2 digits
or
\d{2}\.\d 2 digits followed by a dot and 1 digit
or
[^.]+ any number of digits not up to a dot.
First divide your number and then call ToString() before the regex.
Simple way to implement this just write
ToString("f2") for two decimal number just change this fnumber to get your required number of decimal values with integer values also.

C# Formatting numbers with spaces delimiting thousands

I'm trying to format a decimal with the following requirements:
Thousands are separated by spaces " "
Decimal point is delimited by a
comma "," (this is achieved by using the appropriate culture, in this
case Croatian)
There are two digits after the decimal point.
So far I got this:
String.Format(new CultureInfo("hr-HR"), "{0:# ##0.00}", input)
This works well if the number has 4 or more digits before the decimal point. For example the value 5500.5 gives me "5 500,50" and -5500.5 gives me "-5 500,50", which is what I want.
But if the number has fewer digits, I get a white space in front of the number. For example 500.5 gives me " 500,50" instead of "500,50". And with a negative number, the space is put between the minus sign and the digits: -500.5 gives me "- 500,50". So I can't simply trim the result. How can I achieve what I need?
You can use a custom NumberFormatInfo to format numbers.
var nfi = new NumberFormatInfo();
nfi.NumberGroupSeparator = " "; // set the group separator to a space
nfi.NumberDecimalSeparator = ","; // set decimal separator to comma
And then format the number using
number.ToString("N2", nfi); // numeric format with 2 decimal digits
This gives you
(5500.5).ToString("N2", nfi) // "5 500,50"
(-500.5).ToString("N2", nfi) // "-500,50"
(-5500.5).ToString("N2", nfi) // "-5 500,50"
The simplest approach may be to just check if input is over a 1000 / less than -1000 before formatting it this way.
if(input >= 1000 || input <= -1000){
// use String.Format(new CultureInfo("hr-HR"), "{0:# ##0.00}", input)
}else{
// just use input.ToString()?
}
There's probably a way to coerce string.format into doing what you want, but why overcomplicate the issue?

How to add thousands separator to string value which may contain floating points

I have a string series of values which may or may not contain a floating point number. I want to add the thousands separator to this numeric string. I want to have the value with thousands separators and floating point number only when it's there. How can I do this?
Examples:
Input: 23456.78
Output: 23,456.78
Input: 23456
Output: 23,456
Try parsing to decimal (or double) and then format back to the required representation ("#,#.##########" format string in your case):
String input = "23456.78";
// 23,456.78
String output = decimal
.Parse(input, CultureInfo.InvariantCulture)
.ToString("#,#.##########", CultureInfo.InvariantCulture);

How to Convert Positive or Negative Scientific Notation to Number in C#? [duplicate]

This question already has answers here:
Parse a Number from Exponential Notation
(10 answers)
Closed 6 years ago.
I have tried this two codes:
1)
Decimal h2 = 0;
Decimal.TryParse("-8.13E-06", out h2);
2)
Decimal.Parse(Convert.ToString(used[row, column].Value), NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint);
But It is not working for -8.13E-06 Value.
Any other better option to convert Scientific Notation to Decimal?
Thanks in Advance.
If your culture uses "." as separator:
decimal d = Decimal.Parse("-8.13E-06", System.Globalization.NumberStyles.Float);
Or you can specify the InvariantCulture:
decimal d = Decimal.Parse("-8.13E-06", System.Globalization.NumberStyles.Float, CultureInfo.InvariantCulture);
or as in your exapmple:
Decimal h2 = 0;
Decimal.TryParse("-8.13E-06", NumberStyles.Float, CultureInfo.InvariantCulture, out h2);
AllowExponent wont work as per this:
https://msdn.microsoft.com/en-us/library/system.globalization.numberstyles(v=vs.110).aspx
Indicates that the numeric string can be in exponential notation. The AllowExponent flag allows the parsed string to contain an exponent
that begins with the "E" or "e" character and that is followed by an
optional positive or negative sign and an integer. In other words, it
successfully parses strings in the form nnnExx, nnnE+xx, and nnnE-xx.
It does not allow a decimal separator or sign in the significand or
mantissa; to allow these elements in the string to be parsed, use the
AllowDecimalPoint and AllowLeadingSign flags, or use a composite style
that includes these individual flags.
System.Globalization.NumberStyles.Float is such a composite style

How to parse number with multiple possible thousandsseparators?

Culture nb-NO has " " (space) as thousands separator (numbergroupseparator, currencygroupseparator etc), but it's very common to also type "." (period).
Decimal separator is ",".
How can I assign multiple thousands separators?
If you know what the separator is or know a list, use Int.TryParse and pass in the different cultures representing the separators. For example:
using System.Globalization;
...
string number; // Contains number to parse
int parsedNumber;
List<CultureInfo> cultures = new List<CultureInfo>()
{
Cultureinfo.InvariantCulture,
new CultureInfo("en-US"),
... // Insert other cultures here
};
CultureInfo matchingCulture = cultures.FirstOrDefault(cultureInfo =>
Int.TryParse(number, out parsedNumber,
NumberStyles.AllowThousands, cultureInfo));
if(matchingCulture != null)
{
// parsedNumber contains the parsed number and matchingCulture contains
// the culture that parsed it
}
If separators are not represented by different cultures, consider using a simple string.Replace() to replace a list of known separators with a single known one, such as a comma. Note that this may have issues, for example, where thousands separators are used with decimal points because some country's conventions conflict.
If you can't find a built-in solution, you can always replace the possible unwanted characters such as , with empty string, then parse the number.

Categories