Adding comma between longer numbers [duplicate] - c#

This question already has answers here:
.NET String.Format() to add commas in thousands place for a number
(23 answers)
Closed 9 years ago.
I'm trying to put comma's between long numbers automatically, but so far without success. I'm probably making a very simple mistake, but so far I can't figure it out. This is the code I currently have, but for some reason I'm getting 123456789 as the output.
string s = "123456789";
string.Format("{0:#,###0}", s);
MessageBox.Show(s); // Needs to output 123,456,789

var input = 123456789;
// these two lines amount to the same thing
Console.WriteLine(input.ToString("N0"));
Console.WriteLine(string.Format("{0:N0}", input));
If, as per your question, you need to start with a string:
var stringInput = "123456789";
var input = int.Parse(stringInput);
// these two lines amount to the same thing
Console.WriteLine(input.ToString("N0"));
Console.WriteLine(string.Format("{0:N0}", input));
You'll possibly also need to take culture into account when parsing/formatting. See the overloads that take an IFormatProvider.

Try this:
string value = string.Format("{0:#,###0}", 123456789);
In your code you are missing the initial { in the format string, and then number formatting options apply to numbers, while your s is a string.
You could convert the string to a number with int.Parse:
int s = int.Parse("123456789");
string value = string.Format("{0:#,###0}", 123456789);
MessageBox.Show(value);

This should work (you need to pass String.Format() a number, not another String):
Int32 i = 123456789;
String s = String.Format("{0:#,###0}", i);
MessageBox.Show(s);
But consider the format string you're using...there are cleaner options available, as others are suggesting.

Look at the number formatting information on MSDN: Standard Numeric Format Strings, or optionally at the custom format strings: Custom Numeric Format Strings.
For custom number formats:
The "," character serves as both a group separator and a number scaling specifier.
double value = 1234567890;
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
// Displays 1,234,567,890
Console.WriteLine(value.ToString("#,##0,,", CultureInfo.InvariantCulture));
// Displays 1,235

There is so much wrong with your code, that's it's hard to describe every detail.
Look at this example:
namespace ConsoleApplication1
{
using System;
public class Program
{
public static void Main()
{
const int Number = 123456789;
var formatted = string.Format("{0:#,###0}", Number);
Console.WriteLine(formatted);
Console.ReadLine();
}
}
}

Related

What is the percentage format string to always display the sign?

I want to display 0.12345 as "+12.3%". Format string "P1" or "p1" gives "12.3%". I have tried both "+P1" and "+p1" to no avail.
string sFoo = 0.12345.ToString("P1");
Update
I should have emphasized that I always want the proper sign, not "+". If the number is -0.12345, "P1" works exactly as I want: "-12.3%".
Not quite using P1, but same result:
0.12345.ToString("+#.#%;-#.#%");
If you prefer at least one leading digit (e.g. "+0.23%" instead of "+.23%"):
0.12345.ToString("+0.#%;-0.#%"));
Same for trailing digits (e.g. "+14.0%" instead of "+14%"):
0.12345.ToString("+0.0%;-0.0%"));
Reference: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#the--section-separator
var num = 0.12345;
var sign = num > 0 ? "+" : "";
var output = $"{sign}{num.ToString("P1")}";
I'm afraid there is no format string to display the positive sign. I've searched in NumberFormatInfo if some custom format could accept this, but with no avail.
You can however build some extension methods to fit your needs :
public static string ToSignedPercent(this double input)
{
return $"{(input >= 0 ? "+" : "")}{input.ToString("P1")}";
}
// ...
Console.WriteLine((0.12345).ToSignedPercent()); // +12.3%
Console.WriteLine((-0.6789).ToSignedPercent()); // -67.9%
Fiddle
Put the following in your main method. basically this approaches just sets the variable sFoo to have format of percentage with two decimals.
string sFoo = String.Format("Value: {0:P2}.", 0.12345); // formats as 12.35%
Console.WriteLine(sFoo);

Read out one Line for two variables but one is double and the other one is a string

I wanted to read out two variables from one line, so I used var.
I encountered some difficulties with the second variable beeing a double and the first one beeing a string.
var inputParts = Console.ReadLine().Split(' ');
temp0 = inputParts[0];
temp1 = Convert.ToDouble(inputParts[1]);
What's wrong with this type of code? Visual Studio didn't help me out there.
Thank you in forward :)
temp1 = double.Parse(inputParts[1]);
I guess that temp0 and temp1 do not have the right type. For that code to work they should be defined as:
string temp0;
double temp1;
Edit: based on your comment below what you're actually getting is a run time exception because the string you're trying to parse does not match the expected format of a double.
You could print inputParts[1] to check what it actually contains.
If you're expecting your double to look like 1.0 (with a . for decimal separator) then you should do
temp1 = float.Parse(inputParts[1],CultureInfo.InvariantCulture);
If you don't use CultureInfo.InvariantCulture then the way that the double is parsed will depend on the user's locale. The locale might be such that it expects a comma to be the decimal separator e.g. "1,0" so when it sees a '.' it will throw an exception.
Note that you will need to add
using System.Globalization;
Here is a complete program that works:
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
string temp0;
double temp1;
var inputParts = Console.ReadLine().Split(' ');
temp0 = inputParts[0];
temp1 = double.Parse(inputParts[1], CultureInfo.InvariantCulture);
Console.WriteLine(string.Format("The double was parsed as {0}", temp1));
}
}
If you run this and enter input like
firstPartThatIsIgnored 100.5
You will get output
The double was parsed as 100.5
What language are you using? Presuming you're splitting based on a Space, I'd parse it as a String array. Check and see the type of the part first, before trying to convert to avoid exceptions.
string input = "x 3.3 z 2";
string[] cars = input.split(" ");
double x = double.TryParse(cars[1]);
If you are trying to just extract a double from a random string of input, you could use something like this:
string inputData = "sfdsdf2.2222sfdsfs";
var data = Regex.Match(inputData, "^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$").Value;

How can i convert string value to rial money unit?

I'm beginner in c# and have this value of string:
123456
but want convert that string to my country money, want convert that string value to this:
123,456
always split three numbers with comma for example, if string number is this:
1234567890
Show to user this:
1,234,567,890
How can i write code that purpose?
I would suggest convert it to int (or long) first and then use ToString() and supply required format.
int number = int.Parse(numberString); //ex..
number.ToString("N0"); // 1,000,000
If you're asking about culture-specific formatting, then you could do this.
number.ToString("N0", CultureInfo.CreateSpecificCulture("es-US"));
You can explore more on standard numeric formats
Example code
Use the standard formatters and the CultureInfo for the desired country.
e.g
int i = int.Parse("123456");
string money = i.ToString("C", CultureInfo.CreateSpecificCulture("fr-Ir"));
Or if the system culture is fr-Ir
string money = i.ToString("C");
Which is the same as
string money = i.ToString("C", CultureInfo.CurrentCulture);
Or if you want to use the UI culture (the culture of the requesting browser)
string money = i.ToString("C", CultureInfo.CurrentUICulture);
Since you want to convert your value to currency, I would suggest using "C" of string formats provided by .NET.
123456.125M.ToString("C"); // $123,456.13
Sign infront of the string will be defined by the culture of your machine. More information here.
On the other hand, there is another solution to add your own custom format:
123456.125M.ToString("#,0.################"); // 123,456.125
It is not the clean way, but I have not since found a correct way of actually formating this in generic way.
Side note: for currency handling it is generally considered a good practise to use decimal. Since it does not have a floating point issue.
Please try this one hope will help
Just whats inside the void method
using System.Linq;
public class Program
{
public void ABC()
{
var data = "123456789";
const int separateOnLength = N;
var separated = new string(
data.Select((x,i) => i > 0 && i % separateOnLength == 0 ? new [] { ',', x } : new [] { x })
.SelectMany(x => x)
.ToArray()
);
}
}

Format numeric string with comma separator for indian numbering system

I have a number value in string as
string strNum = "12345678.90";
I want to format it with comma separator using regex in String.Format()
On using "{0:n0}" format in
String.Format("{0:n0}", Convert.ToDouble(strNum));
it is giving me output as "12,345,679"
Instead of this i want output as "1,23,45,678.90". After thousand's place i want comma separator after 2 digits each for lakhs, crores and so on
How can this be achieved?
var s = String.Format(new CultureInfo( "en-IN", false ), "{0:n}", Convert.ToDouble("12345678.90"));
For such a typical way I would write a specialized function that transforms a number into the string you propose.
I even would suggest to make the item a class, having the value represented as float or by different items like lakhs, crores etc.
And then make a ToString method to output it the way you want.
Example (not tested):
class SpecialNumber
{
int _lakhs;
int _crores;
int _another_unit;
int _rest;
public SpecialNumber(int lakhs, int crores, int another_unit, int rest)
{
_lakhs = lakhs;
_crores = crores;
_another_unit = another_unit;
_rest = rest;
}
public string ToString()
{
// Check for exact formatting.
return String.Format("{0:2},{1:2},{2:3}.{0:2}",
_laksh, _crores, _another_unit, _rest);
}
My best bet would be to use the String.Format along with '#' as such:
String.Format(0:##,##,##,##,##,###.##)
The '#' is a digit placeholder and will not show a zero (or anything else) if the number is not large enough.
See MSDN custom numeric format strings for further details.
you seem to format according to hindi culture.
so set your culture, or provide the culture to String.Format, like
String.Format(CultureInfo.GetCultureInfo( "<yourculture>" ), "{0:n}", Convert.ToDouble(strNum));
With this code you can change an amount string to Indian standard comma separated value; use culture "hi-IN" and the format "{0:#,0.00}"
here strNum is my string value amount.
string.Format( System.Globalization.CultureInfo.CreateSpecificCulture("hi-IN"), "{0:#,0.00}", Convert.ToDouble(strNum)

parsing a string into int/long using custom format strings

In C#.Net, here's a simple example of how to format numbers into strings using custom format strings:
(example taken from: http://www.csharp-examples.net/string-format-int/)
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"
Is there a way to convert this formatted string back into a long/integer ? Is there someway to do this :
long PhoneNumber = Int32.Parse("89-5871-2551", "{0:##-####-####}");
I saw that DateTime has a method ParseExact which can do this work well. But I did not see any such thing for int/long/decimal/double.
You can regex out all of the non numeric numbers, and what you're left with is a string of numbers that you can parse.
var myPhoneNumber = "89-5871-2551";
var strippedPhoneNumber = Regex.Replace(myPhoneNumber, #"[^\d]", "");
int intRepresentation;
if (Int32.TryParse(strippedPhoneNumber, out intRepresentation))
{
// It was assigned, intRepresentation = 8958712551
// now you can use intRepresentation.
} else {
// It was not assigned, intRepresentation is still null.
}
Well, you can always do
long PhoneNumber = Int32.Parse("89-5871-2551".
Replace(new char[]{'-','+',whatever..}).Trim());
By the way, considering that you're parsing a string received from some IO, I would suggest to use more secure (in terms of conversion) Int32.TryParse method.
The way like you described doesn't actually exist.
Just Regex out all of the non-numeric characters, then parse that string.

Categories