Add numeric strings in C# and preserve formating - c#

I have an issue where I need to add two numeric strings "$1,234.56" and "$9,876.54" and get a string "$11,111.10"
I can convert the strings to numbers, perform the addition, but I don't know of a good way to preserve the formatting when I ToString() the result. I can add a couple of if statements along the lines: does the input have dollar sign, decimal point, percent sign and construct the format string accordingly, but this is clunky and will fail if we ever need to support more than one number format.
Does anyone know how to add numeric strings and preserve formatting?
EDIT: To answer the questions. The format of all strings being added at a given time is the same ie: I don't need to worry about adding $ and £ (in fact £ is not currently supported), However, there are several possible formats that are currently supported and more may be added in the future:
$1,234.00; $1,234; 1234; 1,234; 1,234.00; 1234%; 1,234%; 1,234.00%

I would suggest using the first numeric string as a template and create a number format from it:
var posshalves = firstNumericString.Split('.');
var fmthalves = new string[2] { posshalves[0], (posshalves.Length < 2 ? "" : "."+posshalves[1])};
var intfmt = Regex.Replace(fmthalves[0], #"[0-9]", "#");
intfmt = Regex.Replace(intfmt, #"#+", "#");
var decfmt = Regex.Replace(fmthalves[1], "[0-9]", "0");
var format = $"{intfmt}{decfmt}";

Related

string format money , [duplicate]

I need to display a number with commas and a decimal point.
Eg:
Case 1 : Decimal number is 432324 (This does not have commas or decimal points).
Need to display it as: 432,324.00.
Not: 432,324
Case 2 : Decimal number is 2222222.22 (This does not have commas).
Need to display it as: 2,222,222.22
I tried ToString("#,##0.##"), but it is not formatting it correctly.
int number = 1234567890;
number.ToString("#,##0.00");
You will get the result 1,234,567,890.00.
Maybe you simply want the standard format string "N", as in
number.ToString("N")
It will use thousand separators, and a fixed number of fractional decimals. The symbol for thousands separators and the symbol for the decimal point depend on the format provider (typically CultureInfo) you use, as does the number of decimals (which will normally by 2, as you require).
If the format provider specifies a different number of decimals, and if you don't want to change the format provider, you can give the number of decimals after the N, as in .ToString("N2").
Edit: The sizes of the groups between the commas are governed by the
CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes
array, given that you don't specify a special format provider.
Try with
ToString("#,##0.00")
From MSDN
*The "0" custom format specifier serves as a zero-placeholder symbol. If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string. The position of the leftmost zero before the decimal point and the rightmost zero after the decimal point determines the range of digits that are always present in the result string.
The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.*
I had the same problem. I wanted to format numbers like the "General" format in spreadsheets, meaning show decimals if they're significant, but chop them off if not. In other words:
1234.56 => 1,234.56
1234 => 1,234
It needs to support a maximum number of places after the decimal, but don't put trailing zeros or dots if not required, and of course, it needs to be culture friendly. I never really figured out a clean way to do it using String.Format alone, but a combination of String.Format and Regex.Replace with some culture help from NumberFormatInfo.CurrentInfo did the job (LinqPad C# Program).
string FormatNumber<T>(T number, int maxDecimals = 4) {
return Regex.Replace(String.Format("{0:n" + maxDecimals + "}", number),
#"[" + System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + "]?0+$", "");
}
void Main(){
foreach (var test in new[] { 123, 1234, 1234.56, 123456.789, 1234.56789123 } )
Console.WriteLine(test + " = " + FormatNumber(test));
}
Produces:
123 = 123
1234 = 1,234
1234.56 = 1,234.56
123456.789 = 123,456.789
1234.56789123 = 1,234.5679
Try with
ToString("#,##0.###")
Produces:
1234.55678 => 1,234.556
1234 => 1,234
For Razor View:
$#string.Format("{0:#,0.00}",item.TotalAmount)
CultureInfo us = new CultureInfo("en-US");
TotalAmount.ToString("N", us)
Your question is not very clear but this should achieve what you are trying to do:
decimal numericValue = 3494309432324.00m;
string formatted = numericValue.ToString("#,##0.00");
Then formatted will contain: 3,494,309,432,324.00
All that is needed is "#,0.00", c# does the rest.
Num.ToString("#,0.00"")
The "#,0" formats the thousand separators
"0.00" forces two decimal points
If you are using string variables you can format the string directly using a : then specify the format (e.g. N0, P2, etc).
decimal Number = 2000.55512016465m;
$"{Number:N}" #Outputs 2,000.55512016465
You can also specify the number of decimal places to show by adding a number to the end like
$"{Number:N1}" #Outputs 2,000.5
$"{Number:N2}" #Outputs 2,000.55
$"{Number:N3}" #Outputs 2,000.555
$"{Number:N4}" #Outputs 2,000.5551
string Mynewcurrency = DisplayIndianCurrency("7743450.00");
private string DisplayIndianCurrency(string EXruppesformate)
{
string fare = EXruppesformate;
decimal parsed = decimal.Parse(fare, CultureInfo.InvariantCulture);
CultureInfo hindi = new CultureInfo("en-IN");
// string text = string.Format(hindi, "{0:c}", parsed);if you want <b>Rs 77,43,450.00</b>
string text = string.Format(hindi, "{0:N}", parsed); //if you want <b>77,43,450.00</b>
return ruppesformate = text;
}
For anyone looking at this now, and getting the "No overload for method 'ToString' takes 1 argument" when using:
TotalNumber.ToString("N")
My solution has been to use :
TotalNumber.Value.ToString("N")
I often get stuck on this when working directly inside an MVC View, the following wasn't working:
#Model.Sum(x => x.Number).ToString("N")
Whereas this works:
#Model.Sum(x => x.Number).Value.ToString("N")

Remove trailing zeros and thousand separator (comma)

Since I am using this to remove trailing zeros when there is no value behind decimal:
decimal.Parse(variable).ToString("G29")
But it doesn't give thousand separator. For example:
string amount = "54321.00"
string amount2 = "54321.55"
string parsed = decimal.Parse(amount).ToString("G29");
string parsed2 = decimal.Parse(amount2).ToString("G29");
//parsed = 54321
//parsed2 = 54321.55
//my goal
//parsed = 54,321
//parsed2 = 54,321.55
Is there any better format type?
Use a custom format
string format = "#,#.##";
decimal noDecimalPlaces = 54321.00m;
decimal decimalPlaces = 54321.55m;
Console.WriteLine(noDecimalPlaces.ToString(format)); // writes 54,321
Console.WriteLine(decimalPlaces.ToString(format)); // writes 54,321.55
You can read more about formatting decimals on msdn.
The way this works
The latter part .## specifies that you allow up to two decimal places. The former part #,# specifies that you want to separate the integer part of your value.
Note:
The number formatting is still culture specific, so for cultures that use , as the decimal separator and . for digit grouping your numbers will be displayed as 54.321 and 54.321,55 instead. You can find out more about formatting in .NET here.

Remove Decimal form String if equals to ".00"

Im having alot of problems trying to take out the decimal part of my string,
the string comes from a var type in my view like this:
var temp = dashList[index];
#PrintSection(actualDate, Model, String.Format("{0:0.000}", temp.Rubro))**
temp.Rubro is my String part that can be ".00" or ".XX"
however i need to take the decimal part of the string only when its value is ".00"
since i have some values of the dashlist have important decimal parts.
Is there a way to take the decimal part of a string only if it equals to ".00"???
The output im trying to get is:
From XX.00 -> XX
From XX.12 -> XX.12
both kinds are on my list
Try this:
var temp = dashList[index];
#PrintSection(actualDate, Model, String.Format("{0:0.000}", temp.Rubro).Replace(".00", ""))
You can try using
String.Format("{0:G29}", decimal.Parse(temp.Rubro)))
Whereas all the below formats achieve the same results.
string.Format("{0:G29}", decimal.Parse("2.00"))
decimal.Parse("2.00").ToString("G29")
2.0m.ToString("G29")
You can use ToString() with the General ("G") Format Specifier to achieve the desired result. Trailing zeros are truncated when using this format string with a precision specified. In order to prevent rounding in any situations, you will need to set the precision to the maximum allowed for decimals (29).
Simple trick...
You can parse the string and it will automatically remove the decimal places
try following
private static void ParseDouble()
{
string sDouble = "12.00";
double dValue = double.Parse(sDouble);
Console.WriteLine(dValue.ToString());
sDouble = "12.14";
dValue = double.Parse(sDouble);
Console.WriteLine(dValue.ToString());
}
Your output will be
12
12.14
Hope this helps.
I will suggest you to use accounting.js plugging which is pretty straightforward. I have used it in some projects and as of today I cannot complain. Otherwise, you could do something like this,
var x = temp.Replace(".00","").Trim();

Adding comma between longer numbers [duplicate]

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

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