Related
I have the number 123.1234567890129.
I want the result to be 123.123456789012 without the last digit being rounded.
I've tried:
("123.1234567890129").ToString("G15") //123.123456789013
One way that you could do this is to round to 16 like this
("123.1234567890129").ToString("G16").Substring(0, 16);
Since you said double.
Since doubles can have ANY number of digits you must round in some way. (you either round down, as inferred or you round up as in practice for this case)
Since you imply you only want to see the number of precise digits, you must find out how many digits are on each side of the decimal point (0 to 15 on either side)
An extenstion to round down
public static class DoubleExtensions
{
public static double RoundDown(this double value, int numDigits)
{
double factoral = Math.Pow(10, numDigits);
return Math.Truncate(value * factoral) / factoral;
}
}
test case
const int totalDigits = 15;
// why start with a string??
string somestring = "123.1234567890129";
const int totalDigits = 15;
// since the title says 'convert a double to a string' lets make it a double eh?
double d = double.Parse(somestring);
int value = (int)d;
double digitsRight = d - value;
int numLeft = (d - digitsRight).ToString().Count();
int numRight = totalDigits - numLeft;
double truncated = d.RoundDown(numRight);
string s = truncated.ToString("g15");
You can create custom FormatProvider and then create your implementation.
class Program
{
static void Main(string[] args)
{
double number = 123.1234567890129;
var result = string.Format(new CustomFormatProvider(15), "{0}", number);
}
}
public class CustomFormatProvider : IFormatProvider, ICustomFormatter
{
private readonly int _numberOfDigits;
public CustomFormatProvider(int numberOfDigits)
{
_numberOfDigits = numberOfDigits;
}
public object GetFormat(Type formatType) => formatType == typeof(ICustomFormatter) ? this : null;
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (!Equals(formatProvider))
return null;
if (!(arg is double))
{
return null;
}
var input = ((double)arg).ToString("R");
return input.Length > _numberOfDigits + 1 ? input.Substring(0, _numberOfDigits + 1) : input; // +1 because of dot
}
Unfortunately you cannot do in this way:
var result = number.ToString(new CustomFormatProvider(15));
because of value types limitation.. Double supports only CultureInfo and NumberFormatInfo formatters. If you pass different formatter it will return default instance: NumberFormatInfo.CurrentInfo'. You can make small workaround by usingstring.Format` method.
New to the community. First answer here. :)
I think you are looking for something like this. Works with or without decimal. This will cut the digits after the 15th digit only irrespective of length of the number. You can get the user to decide the accuracy by getting the precision value as a user input and performing that condition check accordingly. I used 15 because you mentioned it. Let me know if it works for you. Cheers!
string newstr;
int strlength,substrval;
double number;
string strnum = "123.1234567890129";
strlength = strnum.Length;
if(strlength>15)
{
strlength = 15;
}
substrval = strlength;
foreach(char x in strnum)
{
if(x=='.')
{
substrval++;
}
}
newstr = strnum.Substring(0, substrval);
number=Convert.ToDouble(newstr);
Alife Goodacre, code is printing "123.12345678901" insted "123.123456789012"
there should be Substring(0, 16) insted of Substring(0, 15)
Convert.ToDouble("123.1234567890129").ToString("G16").Substring(0, 16)
OutPut Screen with Code.
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 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 have a string like 000000000100, which I would like to convert to 1.00 and vice versa.
Leading zero will be remove, last two digit is the decimal.
I give more example :
000000001000 <=> 10.00
000000001005 <=> 10.05
000000331150 <=> 3311.50
Below is the code I am trying, it is giving me result without decimal :
amtf = string.Format("{0:0.00}", amt.TrimStart(new char[] {'0'}));
Convert the string to a decimal then divide it by 100 and apply the currency format string:
string.Format("{0:#.00}", Convert.ToDecimal(myMoneyString) / 100);
Edited to remove currency symbol as requested and convert to decimal instead.
you will need to convert it to decimal first, then format it in money format.
EX:
decimal decimalMoneyValue = 1921.39m;
string formattedMoneyValue = String.Format("{0:C}", decimalMoneyValue);
a working example: https://dotnetfiddle.net/soxxuW
decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450
Console output:
It works!
decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);
Output
Order Total: $1,921.39
Once you have your string in a double/decimal to get it into the correct formatting for a specific locale use
double amount = 1234.95;
amount.ToString("C") // whatever the executing computer thinks is the right fomat
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ie")) // €1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("es-es")) // 1.234,95 €
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) // £1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-au")) // $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-us")) // $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ca")) // $1,234.95
Try simple like this
var amtf = $"{Convert.ToDecimal(amt):#0.00}";
string s ="000000000100";
decimal iv = 0;
decimal.TryParse(s, out iv);
Console.WriteLine((iv / 100).ToString("0.00"));
//Extra currency symbol and currency formatting: "€3,311.50":
String result = (Decimal.Parse("000000331150") / 100).ToString("C");
//No currency symbol and no currency formatting: "3311.50"
String result = (Decimal.Parse("000000331150") / 100).ToString("f2");
you can also do :
string.Format("{0:C}", amt)
Try something like this:
decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);
In my case, I used this string format to display currency from decimal values without the symbol.
String format:
string.Format("{0:#,##0.00}", decimalValue)
Example:
var decimalNumbers = new decimal[] { 1M, 10M, 100M, 1000M,10000M,100000M,1000000M,1000000000M };
foreach (var decimalNumber in decimalNumbers)
{
Console.WriteLine(string.Format("{0:#,##0.00}", decimalNumber));
}
Parse to your string to a decimal first.
var tests = new[] {"000000001000", "000000001005", "000000331150"};
foreach (var test in tests)
{
Console.WriteLine("{0} <=> {1:f2}", test, Convert.ToDecimal(test) / 100);
}
Since you didn't ask for the currency symbol, I've used "f2" instead of "C"
try
amtf = amtf.Insert(amtf.Length - 2, ".");
private string cxp(string txt) {
try
{
decimal n;
n = Math.Round( Convert.ToDecimal( txt),2);
string newTxt;
newTxt = Convert.ToString(n);
//txt = txt.Replace(",", ".");
//string newtxt = string.Format("{0:#.00}", Convert.ToDecimal(txt) );
return newTxt.Replace(",", ".");
}
catch (Exception e)
{
MessageBox.Show(e.Message ,"Error al parsear número");
//throw;
return txt;
}
}
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