C# Formatting numbers with spaces delimiting thousands - c#

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?

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.

How to format number separated with comma with positive sign (+) and dollar (sign)?

I'm creating a helper to number format a number separated with a comma with a positive sign (+) and dollar ($). However, I already created that return a negative (-) sign. What I want to achieve a result is a positive (+) sign.
-$100 - I already have.
+$100 - This is the one I want to achieve.
Sample Code:
pricing.Price = 600;
RoomTypeDefaultPrice = 500;
var negative = string.Format(culture, "{0:C0}", pricing.Price - RoomTypeDefaultPrice);
Result: -$100
You're close, you just need to use a conditional format:
The semicolon (;) is a conditional format specifier that applies different formatting to a number depending on whether its value is positive, negative, or zero. To produce this behavior, a custom format string can contain up to three sections separated by semicolons. These sections are described in the following table.
pricing.Price = 600;
RoomTypeDefaultPrice = 500;
var negative = string.Format(culture, "{0:+$#,##;-$#,##;$0}", pricing.Price - RoomTypeDefaultPrice);
It's essentially POSITIVE_FORMAT;NEGATIVE_FORMAT;ZERO_FORMAT
Try it online

C# Reducing numbers in scientific notation from E+### to E+##

Using .ToString("E4") prints a number like 1.2345E+012.
How can I make it print one less number in the exponential part. In other words, print 1.2345E+12.
Thanks!
You can use a custom format string with the E indicator, which takes the minimum number of digits:
double value = 1234567890000;
Console.WriteLine(value.ToString("0.####E+0"));
// 1.2346E+12
You could always store '.ToString("E4")' in a string called "output". Then print "output" character by character until you read a "+" character in "output". Don't print the next character if it's a "0", keep checking for "0"s until you reach something that does not equal (!=) a "0" character and then print the last characters.
Try that code:
var number = 1234567890000;
var exponential = number.ToString("E4");
var splitted = exponential.Split('+');
var result = splitted.Length == 2 ? $"{splitted[0]}+{Convert.ToInt32(splitted[1])}" : exponential;
It takes the number, evaluates the exponential string and removes all leading zeros.
This is done by splitting at the + (if there is one, otherwise it's not neccessary and there won't be any leading zeros) and converting the string, of which the zero shall get removed, to a number. As numbers aren't stored with leading zeros, converting it back to a string removes the leading zeros.
If you want to prevent cases where E+0 is written at the end, check the converted string for 0 and if so use the first part of the splitted string without the last character.

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);

Format double in C#

I have a double value. I want to format this value in the format of x.yz. How do I do this? I keep getting digits truncated. Can someone tell me how to do this in C#?
Thanks!
Digits after decimal point
This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.
// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"
Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.
// max. two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"
Digits before decimal point
If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.
// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567); // "123.5"
String.Format("{0:00.0}", 23.4567); // "23.5"
String.Format("{0:00.0}", 3.4567); // "03.5"
String.Format("{0:00.0}", -3.4567); // "-03.5"
Thousands separator
To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.
String.Format("{0:0,0.0}", 12345.67); // "12,345.7"
String.Format("{0:0,0}", 12345.67); // "12,346"
Zero
Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).
Following code shows how can be formatted a zero (of double type).
String.Format("{0:0.0}", 0.0); // "0.0"
String.Format("{0:0.#}", 0.0); // "0"
String.Format("{0:#.0}", 0.0); // ".0"
String.Format("{0:#.#}", 0.0); // ""
Align numbers with spaces
To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not in double.ToString method). To align numbers to the left use negative number of spaces.
String.Format("{0,10:0.0}", 123.4567); // " 123.5"
String.Format("{0,-10:0.0}", 123.4567); // "123.5 "
String.Format("{0,10:0.0}", -123.4567); // " -123.5"
String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "
Custom formatting for negative numbers and zero
If you need to use custom format for negative float numbers or zero, use semicolon separator „;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.
String.Format("{0:0.00;minus 0.00;zero}", 123.4567); // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"
http://www.csharp-examples.net/string-format-double/
Using format strings is explained in:
Standard Numeric Format Strings
Custom Numeric Format Strings
For example, try:
(0.56789).ToString("F2")
(0.56789).ToString("0.00").
Note that the resulting value is NOT truncated, but rounded in both cases, resulting in "0.57".
string.Format("{0:0.00}",yourdouble);
And maybe you'll find useful stick a paper with this http://john-sheehan.com/blog/wp-content/uploads/msnet-formatting-strings.pdf somewhere in your office
Tried something like this, using ToString?
doubleNumber = -1898300.1937;
Console.WriteLine(doubleNumber.ToString("F2", CultureInfo.InvariantCulture));
// Displays -1898300.19
I'm using Math.Round Method
Math.Round(yourdouble, 2)
You can also specify the rounding rule.
Try this:
number.ToString("0.00");
Also take a look at Custom Numeric Format Strings

Categories