C# sometimes currency format does not work - c#

It seems that sometimes the currency format does not work:
string Amount = "11123.45";
Literal2.Text = string.Format("{0:c}", Amount);
reads 11123.45
it should be:
$11,123.45

That code would never work - because Amount is a string, not a number. The currency format only applies to numbers.
For example:
decimal amount = 11123.45m;
Console.WriteLine(string.Format("{0:c}", amount);
(Note that using double for currencies is almost always a bad idea, as double can't exactly represent many decimal numbers. Decimal is a more appropriate type for financial data.)

It's because Amount is a string instead of a numeric.

This worked for my situation
string Amount = "11123.45";
amount2 = amount.AsDecimal();
string.Format("{0:c}", #amount2)

Related

How to convert decimal to money format

I'm trying to convert a number so it looks like the formatting in money.
I need to take 258000 and make it 2,580.00 or 25000 and make it 250.00 or 360 and make it 3.60
This is what I'm using but it's adding the ".00" at the end of all numbers making 2500 2500.00 but it should be 25.00.
Value = string.Format("{0:##,###.00}", Convert.ToDecimal(Value));
It seems to me that you're just missing the fact that you can divide the user's input by 100 after parsing it:
using System;
class Program
{
static void Main(string[] args)
{
string input = "2500";
decimal cents = decimal.Parse(input); // Potentially use TryParse...
decimal dollars = cents / 100m;
string output = dollars.ToString("0.00");
Console.WriteLine(output); // 25.00
}
}
Note that there are complicated cultural rules around how currency values should be displayed - I would suggest using the C format specifier, using a CultureInfo which is like whatever the users are expecting, but with the NumberFormatInfo.CurrencySymbol set to an empty string.
You should also consider which culture to use when parsing the user's input - it can significantly affect the results if they decide to use grouping separators or decimal separators. Will they always be entering an integer? If so, parse it as an integer too.
double valueOriginal = 260;
Response.Write( (valueOriginal / 100).ToString("C"));
260 = (206/100)
then
(260/100).ToString("C");

C# convert string to decimal 4dp

I need to take a string object and convert it to a decimal to 4 dp.
So for example:
string val = "145.83011";
decimal sss = Math.Round(Convert.ToDecimal(val), 4);
bring back 145.8301 - good
However:
string val = "145.8300";
decimal sss = Math.Round(Convert.ToDecimal(val), 4);
brings back 145.83
I need it to be 145.8300
I need it in a decimal format so can't use string format options.
Thanks
rob
One option would be to use string manipulation three times:
Parse the original text to a decimal value (this will preserve the original number of decimal places)
Use string formatting to end up with a string with exactly 4 decimal places. (Math.Round ensures there are at most 4DP, but not exactly 4DP.)
Parse the result of the formatting to get back to a decimal value with exactly 4DP.
So something like this:
public static decimal Force4DecimalPlaces(string input)
{
decimal parsed = decimal.Parse(input, CultureInfo.InvariantCulture);
string intermediate = parsed.ToString("0.0000", CultureInfo.InvariantCulture);
return decimal.Parse(intermediate, CultureInfo.InvariantCulture);
}
I recoil from using string conversions like this, but the alternatives are relatively tricky. You could either get the raw bits, split out the different parts to find the mantissa and scale, then adjust appropriately... or you could potentially work out some sequence of arithmetic operations to get to the right scale. (Jeppe's approach of multiplying by 1.0000m may well be entirely correct - I just don't know whether it's documented to be correct. It would at least be worth adding in appropriate tests for the sorts of numbers you expect to see.)
Note that the above code will perform round up on halves, as far as I can tell, so 1.12345 will be converted to 1.1235 for example.
Sample with output in comments:
using System;
using System.Globalization;
class Test
{
static void Main()
{
Console.WriteLine(Force4DecimalPlaces("0.0000001")); // 0.0000
Console.WriteLine(Force4DecimalPlaces("1.000000")); // 1.0000
Console.WriteLine(Force4DecimalPlaces("1.5")); // 1.5000
Console.WriteLine(Force4DecimalPlaces("1.56789")); // 1.5679
}
public static decimal Force4DecimalPlaces(string input)
{
decimal parsed = decimal.Parse(input, CultureInfo.InvariantCulture);
string intermediate = parsed.ToString("0.0000", CultureInfo.InvariantCulture);
return decimal.Parse(intermediate, CultureInfo.InvariantCulture);
}
}
Both Convert.ToDecimal and decimal.Parse do preserve trailing zeroes in the string (a System.Decimal can have at most 28-29 digits in total, so in most cases there's still room for all the trailing zeroes).
And Math.Round(..., 4) preserves trailing zeroes up to the fourth place after the decimal period.
Therefore the premise of the question is wrong. Your example does bring back what you want.
In any case, consider specifying the overload that takes in an IFormatProvider as well, and give CultureInfo.InvariantCulture as argument. Then the conversion is independent of the local culture.
If instead you want to handle strings like "145.83" and append trailing zeroes that were not in the string, use:
string val = "145.83";
decimal sss = Math.Round(
decimal.Parse(val, CultureInfo.InvariantCulture) * 1.0000m,
4);
Epilog: If you don't like multiplying and dividing by numbers like 1.0000m, use decimal.GetBits to get the internal representation. Adjust the integer "part" by multiplying or dividing by the appropriate power of ten, and adjust the scale "part" by subtracting or adding the corresponding number. The scale counts the number of places to move the decimal point to the left, starting from the 96-bit integer.

Remove decimal from currency

I am converting data for an export.
The file shows data in cents, not dollars.
So 1234.56 needs to be printed as 123456
Is there a way to do that with string.Format?
Or is the only solution to multiply by 100?
You can use string.Replace(".", string.empty). But that isn't exactly localized. You could add in cases where you check for "," as well for international currency. But that's what I would do.
[Edit]
Also just found this:
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
The "N" numeric specifier allows you to change the symbol used to separate whole number and decimal parts.
<code>
decimal num = 123.456m;
NumberFormatInfo ci = CultureInfo.CurrentCulture.NumberFormat;
ci.CurrencyDecimalSeparator = " "; // You can't use string.Empty here, as it throws an exception.
string str = num.ToString("N", ci).Replace(" ", string.Empty);
</code>
Something like that should do the trick, and is localized!
That's a rendering issue. Certainly multiplying by 100 to get cents will do the job.
The United States uses the decimal point to separate dollars from cents. But not all countries do that. Your "multiply by 100" solution is only correct for currencies that use 100 fractional units to represent a single whole. (Not the case in Japan for yen.)
If it is that simple, just do String.Replace('.','');
if you know that the values will always have 2 Decimal Positions then do this it's very simple
var strVar = 1234.56;
var somevalues = string.Format("{0:######}", strVar * 100);
output = 123456

Convert a string to double

I need help converting a string to double with 7 decimals. I have a string "00000827700000" and need it converted to 82.77
Tried using String.Format() with {0:N7} without success.
It looks like you could use:
decimal x = decimal.Parse(text.Substring(0, 7) + "." +
text.Substring(7),
CultureInfo.InvariantCulture);
That would actually parse it to 82.7700000, as decimal preserves trailing zeroes (to an extent) but maybe that's good enough? It not, you could change the second argument to
text.Substring(7).TrimEnd('0')
Note that I'd strongly recommend you to at least consider using decimal instead of double. You haven't explained what this value represents, but if it's stored as decimal figures which you need to preserve, it smells more like a decimal to me.
Based on the edit, it could be simplified as
var text = "00000827700000";
var x = decimal.Parse(text, CultureInfo.InvariantCulture) / 10000000;
Console.Write(String.Format("{0:N7}", x));

C# Get exact string formation from 'double' type

As I'm working on C#, I have one field named 'Amount'.
double amount = 10.0;
So, I want the result like '10.0' after converting it to string.
If my value
amount = 10.00, then I want result '10.00' after converting it to string.
So, Basically I want exact result in string as it is in double type. (With precisions).
Thanks in advance.
string result = string.Format( "{0:f2}", amount );
What you ask is not possible. A double in C# is a simple 64-bit floating-point value. It doesn't store precision. You can print your value with one decimal places, or two, as other answers describe, but not in a way that's "preserves" the variable's original precision.
string amountString = amount.ToString("N2");
"N2" is the format string used as the first parameter to the .ToString() method.
"N" stands for number, and 2 stands for the number of decimal places.
More on string format's here:
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
As #Michael Petratta points out, double doesn't carry with it the precision of the input. If you need that information, you will need to store it yourself. Then you could reconstuct the input string doing something like:
static public string GetPrecisionString( double doubleValue, int precision)
{
string FormattingString = "{0:f" + precision + "}";
return string.Format( FormattingString, doubleValue);
}

Categories