I need to convert decimal number a to string b folowing:
b must be haven '.' character. Eg:
a = 12 -> b = "12.0"
a = 1.2 -> b = "1.2"
a = 1.234 -> b = "1.234"
How can I do that with 1 command?
b must be haven exactly 10 character. Eg:
a = 101 -> b = "101.000000"
a = 1.234 -> b = "1.23400000"
a = 1.234567891 -> b = "1.23456789"
(Same question with 1)
decimal a = 12;
var b = a.ToString("N1"); // 12.0
a = 1.2m;
b = a.ToString(); // 1.2
a = 101m;
b = a.ToString("N10"); // 101.0000000000
a = 1.234m;
b = a.ToString("N10"); // 1.2340000000
For the second part of your question - where you want a total length of 10 then:
decimal a = 1.234567891m;
int numberOfDigits = ((int)a).ToString().Length;
var b = a.ToString($"N{9 - numberOfDigits}"); //1.23456789
//Or before C# 6.0
var b = a.ToString("N" + (9 - numberOfDigits)); //1.23456789
Basically ((int)number).ToString().Length gives you the amount of digits before the . (converting to int will remove the fractions) and then reducing that from the number of digits after the . (and also -1 for the decimal point itself)
You can use .ToString() to do this task:
decimal aDecimalVal = 10.234m;
string decimalString = aDecimalVal.ToString("#.000"); // "10.234"
aDecimalVal.ToString("#.00"); // "10.23"
aDecimalVal.ToString("#.0000"); // "10.2340"
The number of 0 after the . in the format string will decide the number of places in the decimal string.
Updates: So you want to find the number of digits after the decimal points, So the changes in the code will be like the following:
decimal aDecimalVal = 10.2343455m;
int count = BitConverter.GetBytes(decimal.GetBits(aDecimalVal)[3])[2];
string formatString = String.Format("N{0}",count.ToString());
string decimalString = aDecimalVal.ToString(formatString); // "10.2343455"
I manage to do it using double. Is this what you need?
I don't quite get the second part of your question.
double a = 12;
string b = a.ToString("0.0000000000######");
Console.WriteLine(b);
if you want the result as a string, just parse it and format it to one decimal places:
string strTemp = 12;
double temp = Double.Parse(strTemp, CultureInfo.InvariantCulture);
string result = temp.ToString("N1", CultureInfo.InvariantCulture);
Round off to 2 decimal places eg. 27.658 => 27.66
Ensure that there are always 2 decimal places eg. 12 => 12.00, 12.5 => 12.50
Good fit for currency amounts.
strTemp.ToString("F");
For the first one, if you don't know how many the digits the variable could be, you can have a extension method:
public static string ToSpecificFormat(this decimal value)
{
var count = BitConverter.GetBytes(decimal.GetBits(value)[3])[2];
return value.ToString(count == 0 ? "N1" : "N" + count);
}
This will make sure there is at least 1 digit in the output.
For the second one, the selected answer will fail if the number > 1000000000. This one should work:
public static string ToFixedLength(this decimal value)
{
if (value >= 1000000000m) return value.ToString("N0");
var format = 9 - Math.Floor(value).ToString().Length;
return value.ToString("N" + format);
}
output:
1.234m.ToFixedLength(); // 1.23400000
101m.ToFixedLength(); // 101.000000
123456789123m.ToFixedLength(); // 123,456,789,123
Related
I have a function that returns a double value.
How to take its integer part plus decimal part but removing right zeroes and another digit if it is after fourth decimal place?
21.879653 // 21.8796
21.000000 // 21
21.020000 // 21.02
I tried using regex:
Regex.Replace(
Regex.Match(result.ToString(), #"^\d+(?:\.\d{4})?").Value,
#"0*$", "");
But I haven't had any luck... and I'm sure this is not a task for regex.
Other ideas?
Instead of icky string manipulations, you can just use the standard .NET Numeric Format Strings:
"#"
Digit placeholder
Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.
double a = 21.879653;
double b = 21.000000;
double c = 21.020000;
Console.WriteLine(a.ToString("#0.####"));
Console.WriteLine(b.ToString("#0.####"));
Console.WriteLine(c.ToString("#0.####"));
https://dotnetfiddle.net/n9xrfU
The format specifier before the decimal point is #0, meaning at least one digit will be displayed.
you can use Math.Truncate to remove the unwanted digits. If you only want 4 digits:
double d = 21.879653;
double d2 = Math.Truncate(d * 10000) / 10000;
Console.WriteLine(d2.ToString("#.####"));
Try this. It writes nothing for zero.
internal class Program
{
static void Main()
{
double d = 21.8786;
double d1 = 21.000;
double d2 = 21.02000;
double d3 = 0;
WriteNameAndValue(nameof(d), d.FormatDoubleToFourPlaces());
WriteNameAndValue(nameof(d1), d1.FormatDoubleToFourPlaces());
WriteNameAndValue(nameof(d2), d2.FormatDoubleToFourPlaces());
WriteNameAndValue(nameof(d3), d3.FormatDoubleToFourPlaces());
}
static void WriteNameAndValue(string name, string value)
{
Console.WriteLine($"Name: {name}\tValue: {value}");
}
}
static class DoubleHelper
{
public static string FormatDoubleToFourPlaces(this double d, CultureInfo ci = null)
{
const int decimalPlaces = 4;
if (double.IsInfinity(d) || double.IsNaN(d))
{
var ex = new ArgumentOutOfRangeException(nameof(d), d, "Must not be NaN or infinity");
throw ex;
}
decimal decimalVersion = Convert.ToDecimal(d);
if (decimalVersion == 0)
{
return string.Empty;
}
int integerVersion = Convert.ToInt32(Math.Truncate(decimalVersion));
if (integerVersion == decimalVersion)
{
return integerVersion.ToString();
}
decimal scaleFactor = Convert.ToDecimal(Math.Pow(10.0, decimalPlaces));
decimal scaledUp = decimalVersion*scaleFactor;
decimal truncatedScaledUp = Math.Truncate(scaledUp);
decimal resultingVersion = truncatedScaledUp/scaleFactor;
return resultingVersion.ToString(ci ?? CultureInfo.InvariantCulture);
}
}
I have double variable and its value is :
double d = 0.000000000000056843418860808015;
when i print this variable its print wrong.
d.ToString();
Output : "5.6843418860808E-14"
How to resolve this?
Well if you want to have an output without the exponential notation you need to format your string:
d.toString("F25");
This will give you the "correct" number with up to 25 fractional digits.
0,0000000000000568434188608
Edit: Complete list of formats and conversions are available here and snapshot for you is below.
Original value: 1054.32179
F: 1054.32
F0: 1054
F1: 1054.3
F2: 1054.32
F3: 1054.322
double d = 0.000000000000056843418860808015;
var str = d.ToString("G17");
var value = str.Split('E')[0];
var zeros = Int32.Parse(str.Split('E')[1]);
var outputString = "";
zeros = Math.Abs(zeros);
var addstring = "0.";
for (var i = 0; i < zeros - 1; i++)
{
addstring += '0';
}
value = value.Remove(1, 1);
value = addstring + value;
I have some fields returned by a collection as
2.4200
2.0044
2.0000
I want results like
2.42
2.0044
2
I tried with String.Format, but it returns 2.0000 and setting it to N0 rounds the other values as well.
I ran into the same problem but in a case where I do not have control of the output to string, which was taken care of by a library. After looking into details in the implementation of the Decimal type (see http://msdn.microsoft.com/en-us/library/system.decimal.getbits.aspx),
I came up with a neat trick (here as an extension method):
public static decimal Normalize(this decimal value)
{
return value/1.000000000000000000000000000000000m;
}
The exponent part of the decimal is reduced to just what is needed. Calling ToString() on the output decimal will write the number without any trailing 0. E.g.
1.200m.Normalize().ToString();
Is it not as simple as this, if the input IS a string? You can use one of these:
string.Format("{0:G29}", decimal.Parse("2.0044"))
decimal.Parse("2.0044").ToString("G29")
2.0m.ToString("G29")
This should work for all input.
Update Check out the Standard Numeric Formats I've had to explicitly set the precision specifier to 29 as the docs clearly state:
However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved
Update Konrad pointed out in the comments:
Watch out for values like 0.000001. G29 format will present them in the shortest possible way so it will switch to the exponential notation. string.Format("{0:G29}", decimal.Parse("0.00000001",System.Globalization.CultureInfo.GetCultureInfo("en-US"))) will give "1E-08" as the result.
In my opinion its safer to use Custom Numeric Format Strings.
decimal d = 0.00000000000010000000000m;
string custom = d.ToString("0.#########################");
// gives: 0,0000000000001
string general = d.ToString("G29");
// gives: 1E-13
I use this code to avoid "G29" scientific notation:
public static string DecimalToString(this decimal dec)
{
string strdec = dec.ToString(CultureInfo.InvariantCulture);
return strdec.Contains(".") ? strdec.TrimEnd('0').TrimEnd('.') : strdec;
}
EDIT: using system CultureInfo.NumberFormat.NumberDecimalSeparator :
public static string DecimalToString(this decimal dec)
{
string sep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
string strdec = dec.ToString(CultureInfo.CurrentCulture);
return strdec.Contains(sep) ? strdec.TrimEnd('0').TrimEnd(sep.ToCharArray()) : strdec;
}
Use the hash (#) symbol to only display trailing 0's when necessary. See the tests below.
decimal num1 = 13.1534545765;
decimal num2 = 49.100145;
decimal num3 = 30.000235;
num1.ToString("0.##"); //13.15%
num2.ToString("0.##"); //49.1%
num3.ToString("0.##"); //30%
I found an elegant solution from http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/
Basically
decimal v=2.4200M;
v.ToString("#.######"); // Will return 2.42. The number of # is how many decimal digits you support.
A very low level approach, but I belive this would be the most performant way by only using fast integer calculations (and no slow string parsing and culture sensitive methods):
public static decimal Normalize(this decimal d)
{
int[] bits = decimal.GetBits(d);
int sign = bits[3] & (1 << 31);
int exp = (bits[3] >> 16) & 0x1f;
uint a = (uint)bits[2]; // Top bits
uint b = (uint)bits[1]; // Middle bits
uint c = (uint)bits[0]; // Bottom bits
while (exp > 0 && ((a % 5) * 6 + (b % 5) * 6 + c) % 10 == 0)
{
uint r;
a = DivideBy10((uint)0, a, out r);
b = DivideBy10(r, b, out r);
c = DivideBy10(r, c, out r);
exp--;
}
bits[0] = (int)c;
bits[1] = (int)b;
bits[2] = (int)a;
bits[3] = (exp << 16) | sign;
return new decimal(bits);
}
private static uint DivideBy10(uint highBits, uint lowBits, out uint remainder)
{
ulong total = highBits;
total <<= 32;
total = total | (ulong)lowBits;
remainder = (uint)(total % 10L);
return (uint)(total / 10L);
}
This is simple.
decimal decNumber = Convert.ToDecimal(value);
return decNumber.ToString("0.####");
Tested.
Cheers :)
Depends on what your number represents and how you want to manage the values: is it a currency, do you need rounding or truncation, do you need this rounding only for display?
If for display consider formatting the numbers are x.ToString("")
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx and
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
If it is just rounding, use Math.Round overload that requires a MidPointRounding overload
http://msdn.microsoft.com/en-us/library/ms131274.aspx)
If you get your value from a database consider casting instead of conversion:
double value = (decimal)myRecord["columnName"];
This will work:
decimal source = 2.4200m;
string output = ((double)source).ToString();
Or if your initial value is string:
string source = "2.4200";
string output = double.Parse(source).ToString();
Pay attention to this comment.
Trying to do more friendly solution of DecimalToString (https://stackoverflow.com/a/34486763/3852139):
private static decimal Trim(this decimal value)
{
var s = value.ToString(CultureInfo.InvariantCulture);
return s.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator)
? Decimal.Parse(s.TrimEnd('0'), CultureInfo.InvariantCulture)
: value;
}
private static decimal? Trim(this decimal? value)
{
return value.HasValue ? (decimal?) value.Value.Trim() : null;
}
private static void Main(string[] args)
{
Console.WriteLine("=>{0}", 1.0000m.Trim());
Console.WriteLine("=>{0}", 1.000000023000m.Trim());
Console.WriteLine("=>{0}", ((decimal?) 1.000000023000m).Trim());
Console.WriteLine("=>{0}", ((decimal?) null).Trim());
}
Output:
=>1
=>1.000000023
=>1.000000023
=>
how about this:
public static string TrimEnd(this decimal d)
{
string str = d.ToString();
if (str.IndexOf(".") > 0)
{
str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "0+?$", " ");
str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "[.]$", " ");
}
return str;
}
You can just set as:
decimal decNumber = 23.45600000m;
Console.WriteLine(decNumber.ToString("0.##"));
The following code could be used to not use the string type:
int decimalResult = 789.500
while (decimalResult>0 && decimalResult % 10 == 0)
{
decimalResult = decimalResult / 10;
}
return decimalResult;
Returns 789.5
In case you want to keep decimal number, try following example:
number = Math.Floor(number * 100000000) / 100000000;
Here is an Extention method I wrote, it also removes dot or comma if it`s the last character (after the zeros were removed):
public static string RemoveZeroTail(this decimal num)
{
var result = num.ToString().TrimEnd(new char[] { '0' });
if (result[result.Length - 1].ToString() == "." || result[result.Length - 1].ToString() == ",")
{
return result.Substring(0, result.Length - 1);
}
else
{
return result;
}
}
To remove trailing zero's from a string variable dateTicks, Use
return new String(dateTicks.Take(dateTicks.LastIndexOf(dateTicks.Last(v => v != '0')) + 1).ToArray());
Additional Answer:
In a WPF Application using XAML you could use
{Binding yourDecimal, StringFormat='#,0.00#######################'}
The above answer will preserve the zero in some situations so you could still return 2.00 for example
{Binding yourDecimal, StringFormat='#,0.#########################'}
If you want to remove ALL trailing zeros, adjust accordingly.
The following code will be able to remove the trailing 0's. I know it's the hard way but it works.
private static string RemoveTrailingZeros(string input)
{
for (int i = input.Length - 1; i > 0; i-- )
{
if (!input.Contains(".")) break;
if (input[i].Equals('0'))
{
input= input.Remove(i);
}
else break;
}
return input;
}
string.Format("{0:G29}", decimal.Parse("2.00"))
string.Format("{0:G29}", decimal.Parse(Your_Variable))
try this code:
string value = "100";
value = value.Contains(".") ? value.TrimStart('0').TrimEnd('0').TrimEnd('.') : value.TrimStart('0');
Very simple answer is to use TrimEnd(). Here is the result,
double value = 1.00;
string output = value.ToString().TrimEnd('0');
Output is 1
If my value is 1.01 then my output will be 1.01
try like this
string s = "2.4200";
s = s.TrimStart("0").TrimEnd("0", ".");
and then convert that to float
I am looking for a method that adds zero's up to 16 characters before a decimal, and a minus sign if the value is minus. E.g.,
18,52 becomes 000000000000001852, and
-18,52 becomes-00000000000001852
I have an idea how to implement this by using replacements and if-statements, and using the PadLeft method where characters are padded to the left to what length you specify. But I am not sure how to make it exactly.
What I have right now is this:
static string FormatDecimal(decimal d, int length = 0, char a = '0')
{
var sb = new StringBuilder();
var rounded = decimal.Round(d, 2, MidpointRounding.AwayFromZero);
if (rounded < 0)
{
sb.Append("-");
}
else
{
sb.Append("");
}
var lastPart = rounded.ToString().Replace(",", "").Replace(".", "");
var lengthMiddle = length - sb.Length - lastPart.Length;
for (int i = 0; i < lengthMiddle; i++)
{
sb.Append(a);
}
sb.Append(lastPart);
return sb.ToString();
}
When I look at the code and do Console.WriteLine(FormatDecimal(-18m, 16, '0')) I see that
The code is 1. very long, and 2. it does not work... The rounding fails and just keeps the -18 and no minus sign is added.
I would be very grateful if someone could help me out with this one!
If you want to represent two decimal digits in your string and eliminate the decimal mark, you can simply multiply your number by 100. To pad up to 16 digits, use the D format string:
decimal d = -18.52m;
string s = ((int)(d * 100)).ToString("D16");
Edit: If you only want to pad up to 15 digits for negative numbers, you could use a conditional:
decimal d = -18.52m;
int i = (int)(d * 100);
string s = i.ToString(i >= 0 ? "D16" : "D15");
Alternatively, you could express the conditional within the format string itself using section separators:
string s = i.ToString("0000000000000000;-000000000000000");
Instead of building this yourself, use what's already there. decimal.ToString() will format a number for you:
decimal d = 18.52;
string s = d.ToString("0000000000.##"); // = "0000000018.52"
decimal d = 18.00;
string s = d.ToString("0000000000.##"); // = "0000000018"
You could build your format string using the string constructor:
int length = 10;
string formatString = string.Concat(new string('0', length), ".##")
string s = d.ToString(formatString); // = "0000000018"
Note: this doesn't take care of your rounding, but I'm not clear from the question what your requirement is there.
I have some fields returned by a collection as
2.4200
2.0044
2.0000
I want results like
2.42
2.0044
2
I tried with String.Format, but it returns 2.0000 and setting it to N0 rounds the other values as well.
I ran into the same problem but in a case where I do not have control of the output to string, which was taken care of by a library. After looking into details in the implementation of the Decimal type (see http://msdn.microsoft.com/en-us/library/system.decimal.getbits.aspx),
I came up with a neat trick (here as an extension method):
public static decimal Normalize(this decimal value)
{
return value/1.000000000000000000000000000000000m;
}
The exponent part of the decimal is reduced to just what is needed. Calling ToString() on the output decimal will write the number without any trailing 0. E.g.
1.200m.Normalize().ToString();
Is it not as simple as this, if the input IS a string? You can use one of these:
string.Format("{0:G29}", decimal.Parse("2.0044"))
decimal.Parse("2.0044").ToString("G29")
2.0m.ToString("G29")
This should work for all input.
Update Check out the Standard Numeric Formats I've had to explicitly set the precision specifier to 29 as the docs clearly state:
However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved
Update Konrad pointed out in the comments:
Watch out for values like 0.000001. G29 format will present them in the shortest possible way so it will switch to the exponential notation. string.Format("{0:G29}", decimal.Parse("0.00000001",System.Globalization.CultureInfo.GetCultureInfo("en-US"))) will give "1E-08" as the result.
In my opinion its safer to use Custom Numeric Format Strings.
decimal d = 0.00000000000010000000000m;
string custom = d.ToString("0.#########################");
// gives: 0,0000000000001
string general = d.ToString("G29");
// gives: 1E-13
I use this code to avoid "G29" scientific notation:
public static string DecimalToString(this decimal dec)
{
string strdec = dec.ToString(CultureInfo.InvariantCulture);
return strdec.Contains(".") ? strdec.TrimEnd('0').TrimEnd('.') : strdec;
}
EDIT: using system CultureInfo.NumberFormat.NumberDecimalSeparator :
public static string DecimalToString(this decimal dec)
{
string sep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
string strdec = dec.ToString(CultureInfo.CurrentCulture);
return strdec.Contains(sep) ? strdec.TrimEnd('0').TrimEnd(sep.ToCharArray()) : strdec;
}
Use the hash (#) symbol to only display trailing 0's when necessary. See the tests below.
decimal num1 = 13.1534545765;
decimal num2 = 49.100145;
decimal num3 = 30.000235;
num1.ToString("0.##"); //13.15%
num2.ToString("0.##"); //49.1%
num3.ToString("0.##"); //30%
I found an elegant solution from http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/
Basically
decimal v=2.4200M;
v.ToString("#.######"); // Will return 2.42. The number of # is how many decimal digits you support.
A very low level approach, but I belive this would be the most performant way by only using fast integer calculations (and no slow string parsing and culture sensitive methods):
public static decimal Normalize(this decimal d)
{
int[] bits = decimal.GetBits(d);
int sign = bits[3] & (1 << 31);
int exp = (bits[3] >> 16) & 0x1f;
uint a = (uint)bits[2]; // Top bits
uint b = (uint)bits[1]; // Middle bits
uint c = (uint)bits[0]; // Bottom bits
while (exp > 0 && ((a % 5) * 6 + (b % 5) * 6 + c) % 10 == 0)
{
uint r;
a = DivideBy10((uint)0, a, out r);
b = DivideBy10(r, b, out r);
c = DivideBy10(r, c, out r);
exp--;
}
bits[0] = (int)c;
bits[1] = (int)b;
bits[2] = (int)a;
bits[3] = (exp << 16) | sign;
return new decimal(bits);
}
private static uint DivideBy10(uint highBits, uint lowBits, out uint remainder)
{
ulong total = highBits;
total <<= 32;
total = total | (ulong)lowBits;
remainder = (uint)(total % 10L);
return (uint)(total / 10L);
}
This is simple.
decimal decNumber = Convert.ToDecimal(value);
return decNumber.ToString("0.####");
Tested.
Cheers :)
Depends on what your number represents and how you want to manage the values: is it a currency, do you need rounding or truncation, do you need this rounding only for display?
If for display consider formatting the numbers are x.ToString("")
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx and
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
If it is just rounding, use Math.Round overload that requires a MidPointRounding overload
http://msdn.microsoft.com/en-us/library/ms131274.aspx)
If you get your value from a database consider casting instead of conversion:
double value = (decimal)myRecord["columnName"];
This will work:
decimal source = 2.4200m;
string output = ((double)source).ToString();
Or if your initial value is string:
string source = "2.4200";
string output = double.Parse(source).ToString();
Pay attention to this comment.
Trying to do more friendly solution of DecimalToString (https://stackoverflow.com/a/34486763/3852139):
private static decimal Trim(this decimal value)
{
var s = value.ToString(CultureInfo.InvariantCulture);
return s.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator)
? Decimal.Parse(s.TrimEnd('0'), CultureInfo.InvariantCulture)
: value;
}
private static decimal? Trim(this decimal? value)
{
return value.HasValue ? (decimal?) value.Value.Trim() : null;
}
private static void Main(string[] args)
{
Console.WriteLine("=>{0}", 1.0000m.Trim());
Console.WriteLine("=>{0}", 1.000000023000m.Trim());
Console.WriteLine("=>{0}", ((decimal?) 1.000000023000m).Trim());
Console.WriteLine("=>{0}", ((decimal?) null).Trim());
}
Output:
=>1
=>1.000000023
=>1.000000023
=>
how about this:
public static string TrimEnd(this decimal d)
{
string str = d.ToString();
if (str.IndexOf(".") > 0)
{
str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "0+?$", " ");
str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "[.]$", " ");
}
return str;
}
You can just set as:
decimal decNumber = 23.45600000m;
Console.WriteLine(decNumber.ToString("0.##"));
The following code could be used to not use the string type:
int decimalResult = 789.500
while (decimalResult>0 && decimalResult % 10 == 0)
{
decimalResult = decimalResult / 10;
}
return decimalResult;
Returns 789.5
In case you want to keep decimal number, try following example:
number = Math.Floor(number * 100000000) / 100000000;
Here is an Extention method I wrote, it also removes dot or comma if it`s the last character (after the zeros were removed):
public static string RemoveZeroTail(this decimal num)
{
var result = num.ToString().TrimEnd(new char[] { '0' });
if (result[result.Length - 1].ToString() == "." || result[result.Length - 1].ToString() == ",")
{
return result.Substring(0, result.Length - 1);
}
else
{
return result;
}
}
To remove trailing zero's from a string variable dateTicks, Use
return new String(dateTicks.Take(dateTicks.LastIndexOf(dateTicks.Last(v => v != '0')) + 1).ToArray());
Additional Answer:
In a WPF Application using XAML you could use
{Binding yourDecimal, StringFormat='#,0.00#######################'}
The above answer will preserve the zero in some situations so you could still return 2.00 for example
{Binding yourDecimal, StringFormat='#,0.#########################'}
If you want to remove ALL trailing zeros, adjust accordingly.
The following code will be able to remove the trailing 0's. I know it's the hard way but it works.
private static string RemoveTrailingZeros(string input)
{
for (int i = input.Length - 1; i > 0; i-- )
{
if (!input.Contains(".")) break;
if (input[i].Equals('0'))
{
input= input.Remove(i);
}
else break;
}
return input;
}
string.Format("{0:G29}", decimal.Parse("2.00"))
string.Format("{0:G29}", decimal.Parse(Your_Variable))
try this code:
string value = "100";
value = value.Contains(".") ? value.TrimStart('0').TrimEnd('0').TrimEnd('.') : value.TrimStart('0');
Very simple answer is to use TrimEnd(). Here is the result,
double value = 1.00;
string output = value.ToString().TrimEnd('0');
Output is 1
If my value is 1.01 then my output will be 1.01
try like this
string s = "2.4200";
s = s.TrimStart("0").TrimEnd("0", ".");
and then convert that to float