Format decimal value to string with leading spaces - c#

How do I format a decimal value to a string with a single digit after the comma/dot and leading spaces for values less than 100?
For example, a decimal value of 12.3456 should be output as " 12.3" with single leading space. 10.011 would be " 10.0". 123.123 is "123.1"
I'm looking for a solution, that works with standard/custom string formatting, i.e.
decimal value = 12.345456;
Console.Write("{0:magic}", value); // 'magic' would be a fancy pattern.

This pattern {0,5:###.0} should work:
string.Format("{0,5:###.0}", 12.3456) //Output " 12.3"
string.Format("{0,5:###.0}", 10.011) //Output " 10.0"
string.Format("{0,5:###.0}", 123.123) //Output "123.1"
string.Format("{0,5:###.0}", 1.123) //Output " 1.1"
string.Format("{0,5:###.0}", 1234.123)//Output "1234.1"

Another one with string interpolation (C# 6+):
double x = 123.456;
$"{x,15:N4}"// left pad with spaces to 15 total, numeric with fixed 4 decimals
Expression returns: " 123.4560"

value.ToString("N1");
Change the number for more decimal places.
EDIT: Missed the padding bit
value.ToString("N1").PadLeft(1);

Many good answers, but this is what I use the most (c# 6+):
Debug.WriteLine($"{height,6:##0.00}");
//if height is 1.23 => " 1.23"
//if height is 0.23 => " 0.23"
//if height is 123.23 => "123.23"

All above solution will do rounding of decimal, just in case somebody is searching for solution without rounding
decimal dValue = Math.Truncate(1.199999 * 100) / 100;
dValue .ToString("0.00");//output 1.99

Note the "." could be a "," depending on Region settings, when using string.Format.
string.Format("{0,5:###.0}", 0.9) // Output " .9"
string.Format("{0,5:##0.0}", 0.9) // Output " 0.9"
I ended up using this:
string String_SetRPM = $"{Values_SetRPM,5:##0}";
// Prints for example " 0", " 3000", and "24000"
string String_Amps = $"{(Values_Amps * 0.1),5:##0.0}";
// Print for example " 2.3"
Thanks a lot!

Related

Peso Symbol in C#

if (num1 == 5)
{
Console.WriteLine("\nThe " + num2 + " kilo/s of {0} " + 28 + " per kilo ", "GRAPES");
Console.WriteLine("The total amount is {0}{1}", num2.ToString("en-PHI"),num2*28);
}
num2.ToString("en-PHI")
I try this one but it doesn't work at all .. it just copy the en-PHI..
Sounds like you want to provide the culture en-PHI... although that isn't a valid culture name apparently. Perhaps you just want phi as the language?
var culture = CultureInfo.GetCultureInfo("phi");
var text = string.Format(culture, "The total amount is {0:c}", num2 * 28);
Console.WriteLine(text);
The c format specifier is "currency".
That's the way of printing the currency symbol known for a specific culture... now that might not do exactly what you want, but it's probably a matter of finding the right culture.
If you really just want to hard-code the peso character (U+20B1) you can do that directly:
Console.WriteLine("The total amount is \u20b1{0}", num2);
Now if that prints a "?" it means the current console encoding or font doesn't support the peso symbol. Running this from the command line will set it to UTF-8:
> chcp 65001
Make sure the font you're using supports the character as well.

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.

Line up Characters

I have a combobox made up of two numbers; inches and millimetres. At the moment it is looking hideous. I am wondering if some of the gurus here have anyway of lining the character '|' or at least make it nicer?
A bit of background info, the number inches and millimetres are separate strings which I append together like so:
Size(in) + " (In) | " + Size(mm) + " (mm)"
Possibly the cleanest way would be to format every number to have 3 decimal places for at least inches. This still won't be perfect however since the letter font width won't be perfect, to fix that you'd need to use a monospaced font.
To format to 3dp you can use the following
String.Format("{0:f3}", Size(in)) + " (In) | " + Size(mm) + " (mm)"
Since you have some values that are 2 digits before the decimal you can always use PadLeft to align these, but again this doesn't always work well without a monospaced font..
String.Format("{0:f3}", Size(in)).PadLeft(5, ' ') // or (5, '0')
Use String.PadRight(i); and String.PadLeft(i); where i is a nr. of spaces to "fill":
Example:
// Just to simplify a little, create vars:
var inches = Size(in) + " (In) ";
var mm = " + Size(mm) + " (mm)";
var formatted = inches.PadRight(15) + "|" + mm.PadLeft(15);
Example of output using 15 for the padding value (obviously, you can adjust this as needed):
43 inches | 123 cm
445554 inches | 12345 cm

Format custom numeric string with fixed character count

I need to convert any number in a fixed format with a fixed amount of characters. Means 1500 and -1.5 or 0.025 need to have the same length. I also have to give the format in this form: Format = "{???}";
When i type Format = "{0000}"; i can limit 1500 to "1500", but -1.5 -> "-0001.5" means i have too much numbers after the point.
Negative sign place can be done with Format = "{ 0.0;-0.0; 0.0}".
How can i fix the count of the numbers for different numbers?
The length of the string doesn't matter, the most important is the equal length.
Examples:
1500 -> " 1500.000" or " 1500"
-1500 -> "-1500.000" or "- 1500" or " -1500"
1.5 -> " 1.500" or " 1.5"
-0.25-> " -0.250" or "- 0.25"
0.00005 -> " 0.000" or " 0"
150000-> " 150000.0" or " 150000"
15000000 " 15000000"
Edit:
I want to Format an y-Axis of a Chart. I can't use something like value.ToString("???") i need to use chartArea.AxisY.LabelStyle.Format = "{???}";
Why don't use formatting? "F3" forces 3 digits after decimal point and PadLeft ensures the overall length
Double value = 1500.0;
// 3 digits after decimal point, 9 characters length
String result = value.ToString("F3").PadLeft(9, ' ');
0 -> 0.000
1500.0 -> 1500.000
-1500.0 -> -1500.000
-0.25 -> -0.250
Another (similar) possibility is String.Format:
Double value = 1500.0;
// Put value at place {0} with format "F4" aligned to right up to 9 symbols
String result = String.Format("{0:9,F4}", value);
Try it > result = Math.Round(yourValue, 3);
Check full reference here !
you cannot achieve this by a simple format function
string result = string.Empty;
var array = dec.ToString().Split('.');
if (dec > 0)
{
result = array[0].PadLeft(9).Remove(0, 9);
if (array.Count() > 1)
{
result += '.' + array[1].PadRight(3).Remove(3);
}
}
else
{
result = "-"+array[0].PadLeft(9).Remove(0, 9);
if (array.Count() > 1)
{
result += '.' + array[1].PadRight(3).Remove(3);
}
}

Remove 0s from the end of a decimal value [duplicate]

This question already has answers here:
Remove trailing zeros
(23 answers)
Closed 9 years ago.
I have a decimal value that has a variable number of digits after the ., for example:
0.0030
0.0310
0.0001
1.1200
How can I write a dynamic function that removes 0 in the end of the decimal?
You can also modify the decimal itself so that any ToString() will give you what you want
(more details in my answer here) :
public static decimal Normalize(decimal value)
{
return value/1.000000000000000000000000000000000m;
}
string.Format("{0:0.#####}", 0.0030)
or
var money=1.3000m;
money.ToString("0.#####");
For future reference I recommend the .NET Format String Quick Reference by John Sheehan.
decimal value = 0.0030m;
value.ToString(“G29″);
Edit: The G formatter does work, the only problem is that it jumps to scientific notation if there are too many significant figures in the original decimal. Not so ideal.
See the "The General ("G") Format Specifier" documentation here: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#GFormatString
I'm on lunch, so I did a little test:
decimal d1 = 0.000100m;
decimal d2 = 0.001000000000000000000000m;
decimal d3 = 0.000000000000001000000000m;
Console.WriteLine(Environment.NewLine + "input decimal: 0.000100m");
Console.WriteLine("G " + d1.ToString("G"));
Console.WriteLine("G29 " + d1.ToString("G29"));
Console.WriteLine("0.####### " + d1.ToString("0.#######"));
Console.WriteLine(Environment.NewLine + "input decimal: 0.001000000000000000000000m");
Console.WriteLine("G " + d2.ToString("G"));
Console.WriteLine("G29 " + d2.ToString("G29"));
Console.WriteLine("0.####### " + d2.ToString("0.#######"));
Console.WriteLine(Environment.NewLine + "input decimal: 0.000000000000001000000000m");
Console.WriteLine("G " + d3.ToString("G"));
Console.WriteLine("G29 " + d3.ToString("G29"));
Console.WriteLine("0.####### " + d3.ToString("0.#######"));
Output:
input decimal: 0.000100m
G 0.000100
G29 0.0001
0.####### 0.0001
input decimal: 0.001000000000000000000000m
G 0.001000000000000000000000
G29 0.001
0.####### 0.001
input decimal: 0.000000000000001000000000m
G 0.000000000000001000000000
G29 1E-15
0.####### 0
Hmm, this is a display formatting issue (the zeros are added when you convert the decimal to a string).
You need to see where in code you are seeing the trailing zeros. Is it after a call to .ToString()? Try playing around with the different formatting strings:
.ToString("#");
.ToString("0.00");
.ToString("#.##");
And so on. The best way to do this is just to experiment with the different possible values.
decimal m = 0.030000m;
Console.Write(m.ToString("0.##########"));
Just make sure you have enough #s for the number of decimal places you want to display
I use the following. It ensures that any decimal (for which the max precision is 29 decimal places) will show all available digits of precision without trailing zeros, and without your code needing to have a long ugly string of hash marks.
if (value is Decimal)
value = ((Decimal)value).ToString("0.".PadRight(29, '#'), culture);
public static string GentlyRemoveEndZeros(string input)
{
// if (input == null) return null;
// if (input == "") return "";
if (input.Contains(".")) return input.TrimEnd('0').TrimEnd('.');
return input;
}

Categories

Resources