How to display number in money format - c#

How to display Number with comma in following format in C#.
Ex: 12345678
I want to display this number as 1,23,45,678
Can any one give answer for this.
Thanks.

As I understand, this is an Indian style of formatting the currency.
Console.WriteLine(intValue.ToString("N1", CultureInfo.CreateSpecificCulture("hi-IN")));
where intValue is the number you want to format.
For the same input in your question, you should get exactly "1,23,45,678".

Try this
int number = 12345678 ;
Convert.ToDecimal(number).ToString("#,##0");

string.Format("{0:C}", 12345678)

You may try this:-
Double number = 12345678;
String output = number.ToString("C2");
Check out the Currency Formatter.
The "C" (or currency) format specifier converts a number to a string
that represents a currency amount. The precision specifier indicates
the desired number of decimal places in the result string. If the
precision specifier is omitted, the default precision is defined by
the NumberFormatInfo.CurrencyDecimalDigits property.

You can use Custom Format The Currency Format Specifier C or c using ToString()
From MSDN: Custom Format c or C
Result: A currency value.
Supported by: All numeric types.
Precision specifier: Number of decimal digits.
Default precision specifier: Defined by System.Globalization.NumberFormatInfo.
Try This:
int myVal= 12345678;
string finalVal= myVal.ToString("C");
Console.WriteLine(finalVal);
Try This: if you dont want precision.
int myVal= 12345678;
string finalVal= myVal.ToString("C0");
Console.WriteLine(finalVal);

you can use cultureinfo to show currency with your number
decimal dec = 123.00M;
string uk = dec.ToString("C", new CultureInfo("en-GB"); // uk holds "£123.00"
string us = dec.ToString("C", new CultureInfo("en-US"); // us holds "$123.00"

Well, a very dirty solution, but could not figure if there is a format for this.
So I take last 3, then by packs of two :
int number = 212345678;
string semiRes = number.ToString();
var lastThree = semiRes.Substring(semiRes.Length - 3, 3);
List<string> resulatArray = new List<string>();
resulatArray.Add(lastThree);
semiRes = semiRes.Substring(0, semiRes.Length - 3);
for (int i = 2; i <= semiRes.Length + 2; i = i + 2)
{
var start = semiRes.Length - i;
var len = 2;
if (start < 0)
{
len = 2 + start;
start = 0;
}
var nextTwo = semiRes.Substring(start, len);
resulatArray.Insert(0, nextTwo);
}
var result = string.Join(",", resulatArray);
if (result.StartsWith(","))
{
result = result.Substring(1);
}

int number = 123456789;
string Result = number.ToString("#,##0");
Try this.
Hope it helps
using System.Globalization;
NumberFormatInfo info = new NumberFormatInfo();
info.NumberGroupSizes = new int[] { 3, 2 };
int number = 12345678;
string Result = number.ToString("#,#", info);
here you Go...

Related

If decimals are zero ignore but if non-zero, read in the first two

If decimals are zeros, ignore but non zero, need to read in the first two
"35.0" or "35.0000" = 35
"35.0193" = 35.01
"35.98759" = 35.98
Any ideas?
var splitSku4 = value.Split('.');
if (splitSku4.Length > 1)
{
if (!splitSku4[1].StartsWith("0") || !splitSku4[1].StartsWith("00"))
{
sku4 = string.Format("{0}.{1}", splitSku4[0], splitSku4[1].Substring(0, 2));
}
}
stuck at this point
If you have a string that contains a numeric value, you can convert it using one of the Convert methods (e.g. Convert.ToDouble) or by using one of the Parse or TryParse methods associated with the target data type (e.g. Double.Parse).
Examples:
var input = "35.98759";
var number = double.Parse(input);
Or
var number = Convert.ToDouble(input);
Once you have the value stored in a numeric data type, you can remove the least significant digits using Math.Round
var input = "35.98759";
var number = double.Parse(input);
var numberToTwoDecimals = Math.Round(number, 2);
If you always want to round downward, there are a few ways to do it, but the simplest in this case is to subtract 0.005 before rounding the number.
var result = Math.Round(number - 0.005F, 2);
Once the decimals are removed, you can convert back to a string if you want:
var outputString = result.ToString("0.00");
Result:
35.98
Example code on DotNetFiddle
Another way to do it:
var number = 2.56832;
string newnumber = string.Format("{0:0.00}", number )); // formats to 2 decimal places
string[] split = newnumber.Split('.'); //split and remove '.'
if(Convert.ToInt16(split[1]) == 0){ //convert second index to number
var final = split[0];
}else{
var final = newnumber;
}
or in 1 line:
var number = 2.56832;
string newnumber = string.Format("{0:0.00}", number ));
string[] split = newnumber.Split('.'); //split and remove '.'
var final = Convert.ToInt16(split[1]) == 0 ? split[0] : newnumber;

Convert text to integer to compare in C#

The C# program receives a string labeled:
1.2345 V
I need to compare this value using < or > in a 'if' statement.
How do I convert the string above to a integer?
I tried to use:
int anInteger;
anInteger = Convert.ToInt32(textBox1.Text);
anInteger = int.Parse(textBox1.Text);
But it throws the error System.FormatException: incorrect format.
In case you insist on integer (dot in 1.2345 shoud be ignored and final result is 12345):
// Any digits (including, say, Persian ones) are OK
int anInteger = (textBox1.Text
.Where(c => char.IsDigit(c))
.Aggregate(0, (s, a) => s * 10 + (int)char.GetNumericValue(a));
Or
// Only '0'..'9' digits supported
int anInteger = (textBox1.Text
.Where(c => c >= '0' && c <= '9')
.Aggregate(0, (s, a) => s * 10 + a - '0');
You have to remove the V at the end and use decimal.Parse/ TryParse:
decimal d;
bool validFormat = decimal.TryParse(textBox1.Text.TrimEnd('V', ' '), out d);
In my country which uses , as decimal and . as group separator this yields 12345.
If you instead want to ignore anything that is not a digit in a string:
int number = int.Parse(new string(textBox1.Text.Where(char.IsDigit).ToArray()));
Please also notice that depends on your current culture settings you can get different results.
Following code was run with de-DE culture settings
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");
string str = "1.23";
decimal val = decimal.Parse(str);
val.Dump(); // output 123
string str2 = "1,23";
decimal val2 = decimal.Parse(str2);
val2.Dump(); // output 1,23
Following code was run with en-US culture settings
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
string str = "1.23";
decimal val = decimal.Parse(str);
val.Dump(); // output 1.23
string str2 = "1,23";
decimal val2 = decimal.Parse(str2);
val2.Dump(); // output 123
Please use LINQPad to run that code.
you can try -
decimal dec=2;
string str = "3.23456";
dec = Convert.ToDecimal(str.ToString());
int a = Convert.ToInt32(dec);

How to format floating point value with fix number of digits?

Is it possible in C# to format a double value with double.ToString in a way that I have always a fixed number of digits, no matter on which side of the decimal point?
Say I wish 6 digits, I want to have these results:
0.00123456789 gives "0.00123"
1.23456789 gives "1.23457"
123.456789 gives "123.457"
0.0000000123456789 gives "0.00000"
12345678.9 gives "12345679" (on overflow I want to see all digits left of decimalpoint)
4.2 gives "4.20000"
I'm experimenting with double.ToString, but cannot find any suitable format string.
Already tried "G6" (gives sometimes exponential format), "F6" (comes close, but 0.123456789 gives "0.123457" which are 7 digits).
I think some of your examples are wrong.
But I still think that I understand what you want to achieve.
I made an extension method.
public static class StringExtensionMethods
{
public static string ToString(this double d, int numberOfDigits)
{
var result = "";
// Split the number.
// Delimiter can vary depending on locale, should consider this and not use "."
string[] split = d.ToString().Split(new string[] { "." }, StringSplitOptions.None);
if(split[0].Count() >= numberOfDigits)
{
result = split[0].Substring(0, numberOfDigits);
}
else
{
result = split[0];
result += ".";
result += split[1];
// Add padding.
while(result.Count() < numberOfDigits +1)
result += "0";
result = result.Substring(0, numberOfDigits + 1);
}
return result;
}
}
I ran it with your examples:
double d0 = 0.00123456789;
double d1 = 1.23456789;
double d2 = 123.456789;
double d3 = 0.0000000123456789;
double d4 = 12345678.9;
double d5 = 4.2;
Console.WriteLine(d0.ToString(6));
Console.WriteLine(d1.ToString(6));
Console.WriteLine(d2.ToString(6));
Console.WriteLine(d3.ToString(6));
Console.WriteLine(d4.ToString(6));
Console.WriteLine(d5.ToString(6));
This is the output:
0.00123
1.23456
123.456
1.23456
123456
4.20000
I don't think this is the best way to solve it, but I like extension methods.
DoubleConverter class: http://1drv.ms/1yEbvL4
If your goal is to avoid "jumping" of the decimal point:
Use g formating, this does the most sensible thing to do
See where the decimal point is in your resulting string
pad with spaces at the beginning to align the column at the decimal point
As I understand, there is no predefined format that does what I need. So for everyone who is interested, here is the function I ended up with:
public string FormatValue(double d, int noOfDigits)
{
double abs = Math.Abs(d);
int left = abs < 1 ? 1 : (int)(Math.Log10(abs) + 1);
int usedDigits = 0;
StringBuilder sb = new StringBuilder();
for(; usedDigits < left; usedDigits++)
{
sb.Append("0");
}
if(usedDigits < noOfDigits)
{
sb.Append(".");
for(; usedDigits < noOfDigits; usedDigits++)
{
sb.Append("0");
}
}
return d.ToString(sb.ToString());
}

String/Int to double with precision defined onruntime

I have an input type integer that represents a number that needs to be converted to double between 1-100, and the rest is decimal precision.
Example: 1562 -> 15.62 ; 198912 -> 19.8912
Right now, I tried a conversion to string, count the number of characters, take 2 to check how many decimals I have and depending of the result "create" a composite string to get a valid double...
Any idea of there is a better way of resolving convert-precision on runtime.
What about this:
int value = 1562;
decimal d = value;
while (d > 100) {
d /= 10;
}
You can use LINQ Skip and Take like:
string str = "198912";
string newStr = string.Format("{0}.{1}", new string(str.Take(2).ToArray()), new string(str.Skip(2).ToArray()));
double d = double.Parse(newStr, CultureInfo.InvariantCulture);
You can add the checks for length on original string, and also use double.TryParse to see if you get valid values.
If you have an int to begin with then you can use decimal, which would provide you more accurate conversion. Like:
int number = 1562123123;
decimal decimalNumber = number;
while (decimalNumber > 100)
{
decimalNumber /= 10;
}
Here is a mathematical solution. The line lg = Math.Max(lg, 0); changes "2" to return "2.0" instead of "20.0" but I guess that depends on your needs for single digit numbers.
static double ToDoubleBetween1And100(int num)
{
var lg = Math.Floor(Math.Log10(num)) - 1;
lg = Math.Max(lg, 0);
return ((double)num) / Math.Pow(10, lg);
}

Converting number to comma separated values

I need to convert numbers into a comma separated format to display in C#.
For Example:
1000 to 1,000
45000 to 45,000
150000 to 1,50,000
21545000 to 2,15,45,000
How to achieve this in C#?
I tried the below code:
int number = 1000;
number.ToString("#,##0");
But it is not working for lakhs.
I guess you can do this by creating a custom number format info for your needs
NumberFormatInfo nfo = new NumberFormatInfo();
nfo.CurrencyGroupSeparator = ",";
// you are interested in this part of controlling the group sizes
nfo.CurrencyGroupSizes = new int[] { 3, 2 };
nfo.CurrencySymbol = "";
Console.WriteLine(15000000.ToString("c0", nfo)); // prints 1,50,00,000
if specifically only for numbers then you could also do
nfo.NumberGroupSeparator = ",";
nfo.NumberGroupSizes = new int[] { 3, 2 };
Console.WriteLine(15000000.ToString("N0", nfo));
Here's a similar thread to yours add commas in thousands place for a number
and here's the solution that worked perfectly for me
String.Format("{0:n}", 1234);
String.Format("{0:n0}", 9876); // no decimals
If you want to be unique and do extra work that you don't have to here is a function I created for integer numbers you can place commas at whatever interval you want, just put 3 for a comma for each thousandths or you could alternatively do 2 or 6 or whatever you like.
public static string CommaInt(int Number,int Comma)
{
string IntegerNumber = Number.ToString();
string output="";
int q = IntegerNumber.Length % Comma;
int x = q==0?Comma:q;
int i = -1;
foreach (char y in IntegerNumber)
{
i++;
if (i == x) output += "," + y;
else if (i > Comma && (i-x) % Comma == 0) output += "," + y;
else output += y;
}
return output;
}
Have you tried:
ToString("#,##0.00")
Quick and dirty way:
Int32 number = 123456789;
String temp = String.Format(new CultureInfo("en-IN"), "{0:C0}", number);
//The above line will give Rs. 12,34,56,789. Remove the currency symbol
String indianFormatNumber = temp.Substring(3);
An easy solution would be to pass a format into the ToString() method:
string format = "$#,##0.00;-$#,##0.00;Zero";
decimal positiveMoney = 24508975.94m;
decimal negativeMoney = -34.78m;
decimal zeroMoney = 0m;
positiveMoney.ToString(format); //will return $24,508,975.94
negativeMoney.ToString(format); //will return -$34.78
zeroMoney.ToString(format); //will return Zero
Hope this helps,

Categories