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;
}
}
Related
How can I convert a list of decimal values to strings such that:
No decimal point is shown if the value is an integer
Otherwise, the number is formatted to a minimum of two decimal places
For example:
var items = new List<decimal>
{
120.5,
110,
25.356
};
foreach (var item in items)
{
var itemString = item.ToString();
}
This should result in the following string values:
"120.50"
"110"
"25.356"
You can use the decimal.ToString override to specify a formatting.
decimal amount = 120.5m;
string str = amount.ToString("0.00");
This can also be used when using String.Format.
Console.WriteLine("{0:0.00}", amount);
In the case of your first and second rule, it cannot be done on one line.
decimal amount = 120.5m;
string str = amount.ToString("0.00").Replace(".00", String.Empty);
The following extension method should satisfy you requirements. The comments on the code was provided in OP and comments.
public static string ToFormattedString(this decimal d)
{
//The comma is not mandatory. but
var s = d.ToString();
var tokens = s.Split(new[]{"."}, StringSplitOptions.RemoveEmptyEntries);
//if there are no decimal points 12 then there should no be any zeros and periods (.)
if (tokens.Length == 1)
return s;
//I need to remove trailing zeros
var places = tokens[1].TrimEnd('0');
if (places.Length == 0)
return tokens[0];
//if there is only one decimal point ex- 0.5 then it should be displayed as 0.50
if (places.Length == 1)
return d.ToString("F2");
var format = string.Format("F{0}", places.Length);
return d.ToString(format);
}
Used like this
var x = new decimal[]{120.5m, 110, 25.356m};
foreach (var item in x)
Console.WriteLine("{0} => {1}", item.ToString(), item.ToFormattedString());
Output:
120.5 => 120.50
110 => 110
25.356 => 25.356
You can write a method to get you the number of decimal places in the number like this:
private static int GetDecimalPlaces(decimal number)
{
return number.ToString().IndexOf('.') == -1 ? 0 :
number.ToString().Substring(number.ToString().IndexOf('.') + 1).Length;
}
Then you can use Fx specifier where x is the number of decimal places like this:
value1.ToString("F" + GetDecimalPlaces(value1))
Try Me.
Localization
If you care about localization, then use the code below so it will work for any culture since some cultures use , as decimal:
private static int GetDecimalPlaces(decimal number)
{
char decimalSeparator =
Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
var index = number.ToString().IndexOf(decimalSeparator);
return index == -1 ? 0 : number.ToString().Substring(index + 1).Length;
}
There are various formats as shown on MSDN. Here is some code copy pasted from there:
decimal value = 16325.62m;
string specifier;
// Use standard numeric format specifiers.
specifier = "G";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: G: 16325.62
specifier = "C";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: C: $16,325.62
specifier = "E04";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: E04: 1.6326E+004
specifier = "F";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: F: 16325.62
specifier = "N";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: N: 16,325.62
specifier = "P";
Console.WriteLine("{0}: {1}", specifier, (value/10000).ToString(specifier));
// Displays: P: 163.26 %
// Use custom numeric format specifiers.
specifier = "0,0.000";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: 0,0.000: 16,325.620
specifier = "#,#.00#;(#,#.00#)";
Console.WriteLine("{0}: {1}", specifier, (value*-1).ToString(specifier));
// Displays: #,#.00#;(#,#.00#): (16,325.62)
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 need to format a decimal to a minor currency e.g. 10.00 should be 1000.
decimal currency = 10.00m;
System.Console.WriteLine(currency.ToString("######"));
Produces 10, how do I get the decimal points to be added to that?
The solution is as simple as just
* 100
I would create an extension method like this that would produce always the expected result, with the required number of decimals:
public static class DecimalExtension
{
public static string FormatAsMinorCurrency(this decimal value) {
var numberFormat = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
numberFormat.CurrencyDecimalDigits = 2;
numberFormat.CurrencyDecimalSeparator = ".";
numberFormat.CurrencySymbol = "";
numberFormat.CurrencyGroupSeparator = "";
return value.ToString("c", numberFormat).Replace(".", "");
}
}
The results:
1.FormatAsMinorCurrency()
100
10.FormatAsMinorCurrency()
1000
1000000.34102350915091M.FormatAsMinorCurrency()
100000034
How to parse string to decimal so it would work for both formats - w/ commas and periods?
[Fact]
public void foo(){
var a="1,1";
var b="1.1";
Assert.Equal(Parse(a),Parse(b));
}
private decimal Parse(string s){
return decimal.Parse(s,NumberStyles.Any,
CultureInfo.InvariantCulture);
}
output:
Test 'Unit.Sandbox.foo' failed: Assert.Equal() Failure
Expected: 11
Actual: 1,1
You could try that:
private decimal Parse(string s){
s = s.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
return decimal.Parse(s,NumberStyles.Any,
CultureInfo.InvariantCulture);
}
How about this?
private static decimal Parse(string s)
{
s = s.Replace(",", ".");
return decimal.Parse(s);
}
You should get the desired result by modifying the Currency decimal separator to a comma before a parse on a comma decimal string. There are some food resources here:
http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencydecimalseparator.aspx#Y888
You could alternatively implement your own Iformatprovider as discussed here:
http://msdn.microsoft.com/en-us/library/t7xswkc6.aspx
http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx
Oh, or you could do a dirty hack and simply run a string replace on "," with "." ;)
If you have an English-language operating system, this method converts a decimal number with a comma to a dot. If you have Russian, the method converts a decimal number with a dot to a comma.
Console.Write("Input number: ");
string? input = Console.ReadLine();
decimal number = ConvertNumberToCurrentLocale(input);
Console.WriteLine("Result: " + number);
decimal ConvertNumberToCurrentLocale(string? input)
{
string separator = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
switch (separator)
{
case ".":
input = input?.Replace(",", ".");
break;
case ",":
input = input?.Replace(".", ",");
break;
}
decimal.TryParse(input, out var number);
return number;
}
I want to create a string from a decimal, whithout the decimal separator;
1,500.00 should become "150000".
What is the proper format for this? (Whithout string.replace , and .)
Thank you!
try:
decimal d = 1500m;
string s = (100*d).ToString("0");
Two solutions:
Create your own NumberFormatInfo and CultureInfo and pass it along to ToString.
Multiply the number by 100, then use .ToString("0")
What's wrong with String.Replace anyway? It's simple and to the point:
CultureInfo info = CultureInfo.GetCultureInfo("en-US");
decimal m = 1500.00m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "150000"
m = 1500.0m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "15000"
m = 1500.000m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "1500000"
m = 1500.001m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "1500001"
m = 1500.00000000000000000000001m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "150000000000000000000000001"
decimal value = 1500;
Console.WriteLine((value * 100).ToString("0"));