Format decimal value to currency with optional precision - c#

I have c# project. I use ToString("N", CultureInfo.CurrentCulture) for format double value and the result is like 1.254.812,45 .There is no problem. But when I have no precision I don't want to display 1.254.812,00. I want to display only 1.254.812 . How can I do it?

You can use the custom format specifier #, which only returns decimal digits if they exist in the number, both before the decimal point and after.
For example, for de-DE culture:
Console.WriteLine(1254812.45.ToString("#,###.###", CultureInfo.GetCultureInfo("de-DE")));
Console.WriteLine(1254812.0.ToString("#,###.###", CultureInfo.GetCultureInfo("de-DE")));
Output
1.254.812,45
1.254.812
dotnetfiddle

I don't know if there is a direct solution, but the Convert() method I developed provides a solution.
using System;
using System.Globalization;
public class Program
{
public static string Convert(string value)
{
if(value.Split('.')[1].Equals("00"))
return value.Split('.')[0];
return value;
}
public static void Main()
{
double[] inputs = {1254812.00, 1254812.45};
string[] results = {inputs[0].ToString("N", CultureInfo.CurrentCulture), inputs[1].ToString("N", CultureInfo.CurrentCulture)};
Console.WriteLine("{0}\t{1}", Convert(results[0]), Convert(results[1]));
}
}
This code produces the following output:
1,254,812 1,254,812.45

Related

Format Currency string in c# without currency code

I am trying to format a double to currency string in c#
normally, I would use the following code:
using System;
using System.Globalization;
class Demo {
static void Main() {
double value = 234.66;
Console.WriteLine(value.ToString("C", CultureInfo.InvariantCulture));
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
}
}
issue:
The first format prepends an unwanted special caracter: ยค234.66
the later one pepends a dollar sign: $234.660
for normal usecases, I could use several culture infos such as in C# formatting currency given currency code (like USD / GBP / FRF)
unfortunately, Crypto currencies are not supported as far as I know of. So I either look for no currency symbol at all (adding it later to the string) or for a custom currency symbol.
What was quite close was to use balance.ToString("0.##") but in case of 104.10 it would make 104.1 out of it..
var clone = (CultureInfo)CultureInfo.InvariantCulture.Clone();
clone.NumberFormat.CurrencySymbol = "";
var currency = 104.67m;
var stringCurrency = currency.ToString("C", clone);

C# datatype double not printing what I would expect

C# datatype double not printing what I would expect
namespace test
{
class SampleProgram
{
static void Main(string[ ] args)
{
int i = 10;
double d = 34.340;
fun(i);
fun(d);
}
static void fun(double d)
{
Console.WriteLine(d + " ");
}
}
}
Why doe this produce 10 34.34 instead of 10 34.340 ?
To the computer a double with a value of 34.34, 34.340, 34.3400 are all equivalent and represented the same in memory.
What you are running into is the standard problem of the way the runtime gives data back is different than what to display to the user. The way to handle this is to leverage one of the many formatting tools provided by .Net.
You could use the ToString method on the double data type with a custom format string:
double value = 34.34;
Console.WriteLine(value.ToString("0.000")); // 34.340
You could also use custom format string in String.Format:
double value = 34.34;
Console.WriteLine(String.Format("The value is {0:0.000}", value));
you have to apply a custom format to your double value, see string format options and example here
http://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx
e.g. number.ToString("G", CultureInfo.InvariantCulture)

forcing four decimal places for double

I need to display particular value to 4 decimal places for sure.
Here is the code
row["Money"] = StringMgt.ToGlobalizationString("N4", dblMoney);
public static string ToGlobalizationString(string format, double dblNumber)
{
return dblNumber.ToString(format, CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name));
}
Which outputs
1.4305228 to 1.4305 (which is fine!)
0.30704454 to 0.307 (I need to display 4 decimal places consistently)
How do I force it to display four decimal places (ex 0.3070)? I have seen similar posts but did not understand properly.
Thanks.
So the way I understand it you need exactly four decimals, otherwise pad with 0 to the right. So it should be .ToString("0.0000").
I'd use the F-Format specifier:
void Main()
{
double input = 3.213112134;
string result = input.ToGlobalizationString("F4").Dump();
}
public static class Extensions
{
public static string ToGlobalizationString(this double input, string format)
{
return input.ToString(format, CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name));
}
}
This will return a string with 4 decimal points. Change it to your liking.
Use following format:
row["Money"] = StringMgt.ToGlobalizationString("0.0000", dblMoney);
I have tried all the suggestions. If the output value has zero as the 4th decimal its not displaying it. for ex, instead of 0.3070 it is displaying 0.307. If thh fourth decimal is other than zero, it works just fine.
example:
Input value: 0.511519926
Output: 0.5115
Input Value: 0.45895644
Output Value: 0.459
I took off cultural settings and still it didn't work.
I did this and it worked
ClassA.gridTable.Columns[17].DefaultCellStyle.Format = "#,0.0000";
Thanks all for your valuable inputs.

why my parsed Double value is not right?

Im trying to parse a string to a Double.
Here is My code:
string a = "10.23";
double b = Double.Parse(a);
but b is 1023.0 and I dont know why. I would like to get 10.23 as a Double
It's because of your culture settings, you may specify culture for Parse method to get desired output:
string a = "10.23";
double b = double.Parse(a, System.Globalization.CultureInfo.InvariantCulture);
// b == 10.23
In Germany the comma (,) is used as the decimal point, whereas most English cultures and your example use the full stop (.) as the decimal point. Since Double.Parse uses the thread default culture to parse numbers, and the thread default culture is set to German, you're getting the wrong result.
You should instead specify the culture explicitly:
using System.Globalization;
string a = "10.23";
double b = Double.Parse(a, CultureInfo.InvariantCulture);
The invariant culture uses the full stop as the decimal point, so I suggest you use that instead. Or if you get the string from a source known to be written using a particular cultural convention, use that culture instead.
Or your location for number formatted, try this my source:
Ext:
public static class Ext
{
public static double? AsLocaleDouble(this string str)
{
var result = double.NaN;
var format = Thread.CurrentThread.CurrentUICulture.NumberFormat;
double.TryParse(str, NumberStyles.AllowDecimalPoint, format, out result);
return result;
}
}
Test:
class Program
{
static void Main(string[] args)
{
var str = "10,23";
Thread.CurrentThread.CurrentUICulture = new CultureInfo("uz-Cyrl-UZ");
Thread.CurrentThread.CurrentCulture = new CultureInfo("uz-Cyrl-UZ");
Console.WriteLine(str.AsLocaleDouble());
Console.ReadKey();
}
}

How to convert "12,4" to decimal en-Us culture

I have a decimal value ("133,3") stored in string column in the database, in norway culture.
after that user changed the regional setting to english-Us. when I convert "133,3" to decimal using CultureInfo.InvariantCulture, getting invalid value or error.
is there any best way to handle this scenario in C# application?
regards,
Anand
Regardless of the system culture, if you specify CultureInfo.InvariantCulture you won't be able to parse "133,3" as a decimal to 133.3. The same is true for US English.
You could just specify a Norwegian culture when parsing the value (using the overload of decimal.TryParse which takes an IFormatProvider), or (preferrably) change the field in the database to reflect the real data type (a decimal number) instead.
Do you referred to Convert.ToDecimal(), it says like
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] values = { "123456789", "12345.6789", "12 345,6789",
"123,456.789", "123 456,789", "123,456,789.0123",
"123 456 789,0123" };
CultureInfo[] cultures = { new CultureInfo("en-US"),
new CultureInfo("fr-FR") };
foreach (CultureInfo culture in cultures)
{
Console.WriteLine("String -> Decimal Conversion Using the {0} Culture",
culture.Name);
foreach (string value in values)
{
Console.Write("{0,20} -> ", value);
try {
Console.WriteLine(Convert.ToDecimal(value, culture));
}
catch (FormatException) {
Console.WriteLine("FormatException");
}
}
Console.WriteLine();
}
}
}
If you know the culture that was in use when persisting the value, you can use it when parsing it, i.e.:
Convert.ToDecimal("133,3", System.Globalization.CultureInfo.GetCultureInfo("no"));
Of course, you are probably better off changing how the data is stored in the database, to use a floating point number of some form.
Convert.ToDouble(textBox2.Text, new CultureInfo("uk-UA")).ToString(new CultureInfo("en-US"));
This solves your problem: .ToString(New CultureInfo("en-US"))
Hope it's helpful
double _number = 12536,8;
CultureInfo usCulture = new CultureInfo("en-US");
return _number.ToString("N", us);
used below code to fix my issue. I just hard coded the previous currency decimal part. may not be generic. but solved my problem.
public static decimal? ToDecimal1(this string source)
{
CultureInfo usCulture = new CultureInfo("en-US");
if (string.IsNullOrEmpty(source.Trim1()))
return null;
else
return Convert.ToDecimal(source.Replace(",", ".").Trim(), usCulture);
}

Categories