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;
}
Related
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.
I found this question in StackOverFlow but it didn't solve my problem.
How do I format a double to a string and only show decimal digits when necessary?
Weight
0.500
18.000
430.000
by the solution in above url my result show in this form:
Weight
0.5
18
430
and my problem is in decimal digits, I want show decimal digits in 3 digit,like this:
Weight
0.500
18
430
You can use Digit placeholder # with Zero placeholder 0 after dot . in string format.
string num = d % 1 == 0 ? d.ToString(".###") : d.ToString(".000");
Digit placeholder
Replaces the pound sign with the corresponding digit if one is
present; otherwise, no digit appears in the result string.
Zero placeholder
places the zero with the corresponding digit if one is present;
otherwise, zero appears in the result string.
This msdn article Custom Numeric Format Strings explains how the number could be formated.
I think you can't do what you want with single string.Format(). So you can use a clause:
if(weight % 1.0 > 0){
string.Format("{0:0.000}", weight)
}
else {
string.Format("{0:0}", weight)
}
Or even better:
string.Format(weight % 1.0 > 0 ? "{0:0.000}" : "{0:0}", weight)
EDIT: Sorry missed a bit =))
EDIT: If you need to floor result you can use:
string.Format(weight % 1.0 >= 0.001 ? "{0:0.000}" : "{0:0}", weight)
Try
num.ToString("G3") // for 3 significant digits
http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
You can use like below method:
Usage:
string format1 = GetFormat(123.4567);
string format2 = GetFormat(123.45);
string format3 = GetFormat(123.0);
//format1 = 123.46
//format2 = 123.45
//format3 = 123
private static string GetFormat(double d)
{
string format;
if (d == Convert.ToInt32(d))
format = string.Format("{0:0.##}", d);
else
format = string.Format("{0:0.00}", d);
return format;
}
For more information:
http://csharpexamples.com/c-string-formatting-for-double/
http://msdn.microsoft.com/en-us/library/vstudio/0c899ak8%28v=vs.100%29.aspx
I found the solution:
string[] strList = Weight.ToString().Split('.');//or ',' for diffrent regions
if(strList[1] == "000")
str = string.Format("{0:#,0.########}", b);
thank you:)
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.
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!
I have a string which needs a decimal place inserted to give a precision of 2.
3000 => 30.00
300 => 3.00
30 => .30
Given a string input, convert to integer, divide by 100.0 and use String.Format() to make it display two decimal places.
String.Format("{0,0:N2}", Int32.Parse(input) / 100.0)
Smarter and without converting back and forth - pad the string with zeros to at least two characters and then insert a point two characters from the right.
String paddedInput = input.PadLeft(2, '0')
padedInput.Insert(paddedInput.Length - 2, ".")
Pad to a length of three to get a leading zero. Pad to precision + 1 in the extension metheod to get a leading zero.
And as an extension method, just for kicks.
public static class StringExtension
{
public static String InsertDecimal(this String #this, Int32 precision)
{
String padded = #this.PadLeft(precision, '0');
return padded.Insert(padded.Length - precision, ".");
}
}
// Usage
"3000".InsertDecimal(2);
Note: PadLeft() is correct.
PadLeft() '3' => '03' => '.03'
PadRight() '3' => '30' => '.30'
Use tryParse to avoid exceptions.
int val;
if (int.Parse(input, out val)) {
String.Format("{0,0:N2}", val / 100.0);
}
here's very easy way and work well..
urValue.Tostring("F2")
let say..
int/double/decimal urValue = 100;
urValue.Tostring("F2");
result will be "100.00"
so F2 is how many decimal place u want
if you want 4 place, then use F4