Converting number to comma separated values - c#

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,

Related

c# Convert float to ALWAYS have 2 decimal places, even when they are zeros

Lets say I have shipping costs of 10.00 USD. If i pass this value to a float it will become 10. Not "10.00".
I tried:
float shippingRounded = float.Parse("10,00");
But this parses the string to a float and cuts the last two digits.
How can I use a float and still have it have two decimal places, irregardles of what they are?
With:
shippingRounded.ToString(".00")
It will display
10,00
I wrote a function that will always convert a price into the correct format:
public static string ReturnFormattedPrice(string priceWithOutCurrencySymbol)
{
string[] values = new string[2];
List<string> valueList = new List<string>();
valueList.Add("");
valueList.Add("");
// cause it will be either dot or comma
if (priceWithOutCurrencySymbol.Contains(","))
values = priceWithOutCurrencySymbol.Split(",");
else
values = priceWithOutCurrencySymbol.Split(".");
valueList[0] = values[0];
if (values.Length == 1)
valueList[1] = ",00";
else if(values[1].Length == 1)
valueList[1] = "," + values[1] + "0";
else
valueList[1] = "," + values[1];
return valueList[0] + valueList[1];
}

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;

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());
}

Reading two integers at the end of text

I am getting values from the form in the following format:
text 2234-7755
What i want to do is read first four integers than the last four integer values separately.
Please let me know how can i read that. Thanks
string[] nums = text.Split("-");
int num1 = Convert.ToInt32(nums[0]);
int num2 = Convert.ToInt32(nums[1]);
If you want to be safer, you can use int.TryParse
If the number is always at the end, has 8 digits and is separated by - you don't need regex:
string number = text.Substring(text.Length - 9);
string[] both = number.Split('-');
int firstNum, secondNum;
if (both.Length == 2
&& int.TryParse(both[0], out firstNum)
&& int.TryParse(both[1], out secondNum))
{
Console.Write("First number is: {0}\r\nSecond number is: {1}", firstNum, secondNum);
}
Are you looking for something like this?
string text = "text 2234-7755";
var matches = Regex.Matches(text, #"(\d+)");
if (matches.Count == 2)
{
int value1 = Convert.ToInt32(matches[0].Groups[1].Value);
int value2 = Convert.ToInt32(matches[1].Groups[1].Value);
}
use split function and get the first value.
A link for the same
var original="2234-7755";
var intArray = original.Split("-");
int part1 = Convert.ToInt32(intArray[0]);
int part2 = Convert.ToInt32(intArray[1]);
You can also use Int32.TryParse method if you want more control.

How to display just first 2 decimals unequal to 0

How can I display the number with just the 2 not=zero decimals?
Example:
For 0.00045578 I want 0.00045 and for 1.0000533535 I want 1.000053
There is no built in formatting for that.
You can get the fraction part of the number and count how many zeroes there are until you get two digits, and put together the format from that. Example:
double number = 1.0000533535;
double i = Math.Floor(number);
double f = number % 1.0;
int cnt = -2;
while (f < 10) {
f *= 10;
cnt++;
}
Console.WriteLine("{0}.{1}{2:00}", i, new String('0', cnt), f);
Output:
1.000053
Note: The given code only works if there actually is a fractional part of the number, and not for negative numbers. You need to add checks for that if you need to support those cases.
My solution would be to convert the number to a string. Search for the ".", then count zeroes till you find a non-zero digit, then take two digits.
It's not an elegant solution, but I think it will give you consistent results.
Try this function, using parsing to find the # of fractional digits rather than looking for zeros (it works for negative #s as well):
private static string GetTwoFractionalDigitString(double input)
{
// Parse exponential-notation string to find exponent (e.g. 1.2E-004)
double absValue = Math.Abs(input);
double fraction = (absValue - Math.Floor(absValue));
string s1 = fraction.ToString("E1");
// parse exponent peice (starting at 6th character)
int exponent = int.Parse(s1.Substring(5)) + 1;
string s = input.ToString("F" + exponent.ToString());
return s;
}
You can use this trick:
int d, whole;
double number = 0.00045578;
string format;
whole = (int)number;
d = 1;
format = "0.0";
while (Math.Floor(number * Math.Pow(10, d)) / Math.Pow(10, d) == whole)
{
d++;
format += "0";
}
format += "0";
Console.WriteLine(number.ToString(format));

Categories