How to perform currency formatting with string interpolation in c#? - c#

Is it possible to perform string formatting using c#'s string interpolation with a specific CultureInfo?
For example if you are in a en-US System and want the number to be formatted with pt-PT how to I achieve that with string interpolation?

You can use CultureInfo.CreateSpecificCulture for specifying the culture and the C formatter for converting the value into a string with a currency.
double amount = 50.5;
string str = $"{amount.ToString("C", CultureInfo.CreateSpecificCulture("pt-PT"))}";

Interpolated strings can be converted to FormattableStrings, which can be formatted with a IFormatProvider:
var formattableString = (FormattableString)$"{1.1:C}";
var result = formattableString.ToString(new CultureInfo("pt-PT"));
// "1,10 €"

Related

How can i create a dynamic string format in C#

I have as input the string format CST-000000 and an integer with value 1
Upon using
string result = string.Format("CST-000000", 1);
the expected result should be CST-000001 instead of CST-000000
How could i create this string format dynamically?
For example
- CST-000 should produce CST-001
- HELLO000 should produce HELLO001
- CUSTOMER0000 should produce CUSTOMER0001
Assuming that:
You receive your format string from somewhere and you can't control what it looks like
Your format string ends with 1 or more zeros
If the format string is e.g. CST-00000 and your value is 123, you want the result to be CST-00123
You can do something like this:
Inspect your format string, and separate out the stuff at the beginning from the zeros at the end. It's easy to do this with Regex, e.g.:
string format = "CST-000000";
// "Zero or more of anything, followed by one or more zeros at the end of the string"
var match = Regex.Match(format, "(.*?)(0+)$");
if (!match.Success)
{
throw new ArgumentException("Format must end with one or more zeros");
}
string prefix = match.Groups[1].Value; // E.g. CST-
string zeros = match.Groups[2].Value; // E.g. 000000
Once you have these, note the "Zero placeholder" in this list of custom numeric format strings -- you can write e.g. 123.ToString("0000") and the output will be 0123. This lets you finish off with:
int value = 123;
string result = prefix + value.ToString(zeros);
See it on dotnetfiddle
String.Format requires a placeholder {n} with a zero-based argument number. You can also add it a format {n:format}.
string result = String.Format("CST-{0:000000}", 1);
You can also use String interpolation
string result = $"CST-{1:000000}"
The difference is that instead of a placeholder you specify the value directly (or as an expression). Instead of the Custom numeric format string, you can also use the Standard numeric format string d6: $"CST-{1:d6}"
If you want to change the format template dynamically, String.Format will work better, as you can specify the format and the value as separate arguments.
(Example assumes an enum FormatKind and C# >= 8.0)
int value = 1;
string format = formatKind switch {
FormatKind.CstSmall => "CST-{0:d3}",
FormatKind.CstLarge => "CST-{0:d6}",
FormatKind.Hello => "HELLO{0:d3}",
FormatEnum.Customer => "CUSTOMER{0:d4}"
};
string result = String.Format(format, value);
Also note that the value to be formatted must be of a numeric type. Strings cannot be formatted.
See also: Composite formatting
It seems .toString("CST-000"), .toString("HELLO000") and so on, does the trick.
ToString and String.Format can do much more than use predefined formats.
For example :
string result = string.Format("CST-{0:000000}", 1);
string result = 1.ToString("CST-000000");
Should both do what you want.
(Of course you could replace "1" by any variable, even a decimal one).

C# 6 how to format double using interpolated string?

I have used interpolated strings for messages containing string variables like $"{EmployeeName}, {Department}". Now I want to use an interpolated string for showing a formatted double.
Example
var aNumberAsString = aDoubleValue.ToString("0.####");
How can I write it as an interpolated string? Something like $"{aDoubleValue} ...."
You can specify a format string after an expression with a colon (:):
var aNumberAsString = $"{aDoubleValue:0.####}";
A colon after the variable specifies a format,
Console.Write($"{aDoubleValue:0.####}");
Or like this:
Console.Write($"{aDoubleValue:f4}");

How to make string of specified length from another string c#

For example I have strings like:
"5", "8", "14", "260"
and I want to get result like:
"ST00000005", "ST00000008", "ST00000014", "ST00000260"
result string length is 10 chars. How can I do it?
I would store it as int not as string. Then you can use ToString with the appropriate format specifier D8. That has f.e. the advantage that you can increase the number:
int number = 5;
string result = String.Format("ST{0}", number.ToString("D8"));
or without ToString but only String.Format:
string result = String.Format("ST{0:D8}", number);
Read: Standard Numeric Format Strings especially Decimal ("D") Format Specifier
If you need to convert a string to int use int.Parse or int.TryParse.
For the sake of completeness, if you have to use strings use String.PadLeft(8, '0'):
string numStr = "5";
String result = String.Format("ST{0}", numStr.PadLeft(8, '0'));
int number = 5; // put the number here
string result = $"ST{number:0000000#}";
// Or:
string result = $"ST{number:D8}";
This does exactly what you want.
EDIT: Keep in mind that this is only possible in C#6
You can do this like
string s = "215";
s = s.PadLeft(8, '0').PadLeft(9,'T').PadLeft(10,'S');
Use string.Format() together with a custom format string.

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)

formatting string in C#?

I've a predefined string format. For instance '>>>,>>>,>>9.99' this means that the system should display string in this '500,000,000.10'. The format can change based on the users using it. How can I write a common function to display stings on the given format passing
the input value and the format as the parameter using C#
You can use the ToString method with a standard or custom format string
For example:
string format = "{0:000,000,000.00}";
string val = 12.3456;
Console.WriteLine(string.Format(format, value)); // it prints "000,000,123.23"
You can read more about formating values here http://www.csharp-examples.net/string-format-double/
decimal value = 1.2345;
string rounded = value.ToString("d2");
private string sDecimalFormat = "0.00";
decimal d = 120M;
txtText.Text = d.ToString(sDecimalFormat);
You could then have a setting for decimal format eg:
txtText.Text = d.ToString(Settings.DecimalFormat);
String.formate can be used for formating.
Go there if you want examples
http://www.csharp-examples.net/string-format-double/
I think the following might work:
String result = String.Format(fmt.Replace('>', '#').Replace('9', '0'), inpString);
fmt being the format you want to use and inpString being the string entered by the user.
Just replace the > with # and the 9 with 0 and it'll be a valid .Net formatstring.
There is a Format method on String.
String.Format("{0:X}", 10); // prints A (hex 10)
There are several methods to format numbers, date...
I dont seem to understand how you can make 500,000,000.10 from >>>,>>>,>>9.99' but I believe the answer would be
But I assume something you are looking for is: string.Format("500,000,00{0:0.##}", 9.9915)
You can then make a method like
Public string GetString(string Format, object value)
{
return string.Format(Format, value);
}
Something like this?

Categories