Please take a look at the following line of code:
TotalFormatted = totalExpenses.ToString("C3", CultureInfo.CreateSpecificCulture("en-GB"))
I am expecting this to output a number as a formatted string with the pound symbol (£1,500) but instead it is outputting GBP1,500
How can I ensure it outputs the actual symbol instead of GBP?
I settled for the following which correctly formats the string with the pound symbol:
TotalFormatted = totalExpenses.ToString("\u00A3#,##0.00", CultureInfo.CreateSpecificCulture("en-GB"))
Related
I have a json file that include emoji when I want to deserialize it , it could not deserialize emoji to string.
my code is:
var mystring ={"message":"jjasdajdasjdj laslla aasdasd ssdfdsf!!! 🙌\u{1F3FD}", "updated_time":"2015-04-14T22:37:13+0000", "id":"145193995506_148030368559"}
FaceBookIdea ideaDetails = JsonConvert.DeserializeObject<FaceBookIdea>((mystring).ToString());
the error is :
{"Input string was not in a correct format."}
when I remove emoji it works well.
Thank a lot for your help
Your problem is that this portion of your message string does not conform to the JSON standard:
"\u{1F3FD}"
According to the standard, \u four-hex-digits represents a unicode character literal given by the hex value of its code point. Your string \u{1F3FD} with its curly braces does not conform to this convention, and so Json.NET throws an exception upon trying to parse it. You will see a similar error if you upload your JSON to https://jsonformatter.curiousconcept.com/.
Thus it would seem, to fix your JSON to make it conform to the standard, you need to format your character like \uXXXX using the appropriate 4 hex digits. However, your character, U+1F3FD, is larger than 0xFFFF and does not exist on the Unicode Basic Multilingual Plane. It cannot be represented as a single 4-digit hex number. c# (and utf-16 in general) represents such Unicode characters as surrogate pairs -- pairs of two two-byte chars. You will need to do the same here. The UTF-16 (hex) representation of your character is
0xD83C 0xDFFD
Thus your JSON character needs to be:
\uD83C\uDFFD
And for your entire string:
{"message":"jjasdajdasjdj laslla aasdasd ssdfdsf!!! 🙌\uD83C\uDFFD", "updated_time":"2015-04-14T22:37:13+0000", "id":"145193995506_148030368559"}
i have value stored in string format & i want to convert into decimal.
ex:
i have 11.10 stored in string format when i try to convert into decimal it give me 11.1 instead of 11.10 .
I tried it by following way
string getnumber="11.10";
decimal decinum=Convert.ToDecimal(getnumber);
i tried this also
decinum.ToString ("#.##");
but it returns string and i want this in decimal.
what could be the solution for this?
As already commented 11.1 is the same value as 11.10
decimal one=11.1;
decimal two=11.10;
Console.WriteLine(one == two);
Will output true
The # formatter in the to string method means an optional digit and will supress if it is zero (and it is valid to suppress - the 0 in 4.05 wouldn't be suppressed). Try
decinum.ToString("0.00");
And you will see the string value of 11.10
Ideally you actually want to use something like
string input="11.10";
decimal result;
if (decimal.TryParse(input,out result)) {
Console.WriteLine(result == 11.10);
} else {
// The string wasn't a decimal so do something like throw an error.
}
At the end of the above code, result will be the decimal you want and "true" will be output to the console.
this will work perfectly
string getnumber = "11.10";
decimal decinum = Math.Round(Convert.ToDecimal(getnumber), 2);
A decimal datatype stores a value. The value of 11.1 is identical to that of 11.10 - mathemtically, they're the exact same number, so it's behaving properly.
What you seem to want is to display the number as 11.10, but that's up to the code that displays it - I don't know if you're writing to log file, displaying on a web-page or any other format - but that is independent of the internal representation of the decimal datatype.
there is no solution, This is expected behaviour.
11.10 in string = 11.1 in number
you cant store zeros on the decimal part, otherwise 11.10 would be different than 11.100, which is true if you are talking about strings but not if you are talking about numbers.
I think your problem is on a presentation level only. Why dont you explain better what you want to do.
11.10 expressed as a decimal is 11.1, just like it is 11.100000000000000000000000000000000000.
For mathematical processes, don't worry about how it displays itself. If you are displaying the value then converting it into a string is no biggie either. Remember that
decinum.ToString ("#.##");
is returning a string (from the 'ToString' function) and not converting the 'decinum' to a string.
string getnumber = "11.10";
double decinum = double.Parse(getnumber);
I am currently using ncalc library to do several evaluation and get the result out of it.
Right now I have found a problem where if I have a price in the format "1,234.01" it will fail to evaluate my expression.
The current workaround I've used was to remove the , but I was wondering if there is way to evaluate a currency without having to remove the , for example:
decimal price = 0;
if (!decimal.TryParse(iPrice.Text, out price))
{
MessageBox.Show("Price is not formatted correctly...");
return;
}
decimal currency = 0;
if (!decimal.TryParse(iCurrency.Text, out currency))
{
MessageBox.Show("Currency is not formatted correctly...");
return;
}
string formula = iFormula.Text.Replace("Price", price.ToString("n2")).Replace("Currency", currency.ToString("n2"));
Expression exp = new Expression(formula);
exp.Evaluate();
Evaluate fails because of the , from my price where if I remove it, it works just fine.
Sample of the formula:
(((Price+12,9)+((Price+12,9)*0,05)+(((Price+12,9)+((Price+12,9)*0,05))*0,029)+0,45)*Currency)
Stacktrace as requested:
NCalc.EvaluationException was unhandled
Message=mismatched input ',' expecting ')' at line 1:4
mismatched input ',' expecting ')' at line 1:20
mismatched input ',' expecting ')' at line 1:43
mismatched input ',' expecting ')' at line 1:59
missing EOF at ')' at line 1:77
Source=NCalc
StackTrace:
at NCalc.Expression.Evaluate()
Your question is still unclear to me, but I suspect you can fix this just by changing the format you're using when replacing. Change this:
string formula = iFormula.Text.Replace("Price", price.ToString("n2"))
.Replace("Currency", currency.ToString("n2"));
to this:
string formula = iFormula.Text.Replace("Price", price.ToString("f2"))
.Replace("Currency", currency.ToString("f2"));
That will use the "fixed point" format instead of the "number" format. You won't get grouping. Note that grouping isn't part of the number itself - it's part of how you format a number.
I'd also be tempted to specify the invariant culture explicitly, by the way.
As an aside: I haven't used NCalc myself, but if it's really forcing you to specify the numeric values in an expression as text, that sounds pretty poor. I'd expect some sort of parameterization (as per most SQL providers, for example) which should make all of this go away.
No, you cannot have a separator in your decimal literal. The compiler will confuse it with declaring multiple variables with the same type like:
decimal price = 1m, tax = 234m;
If it was a string, however, you could parse it like:
decimal price = Decimal.Parse("1,234.0", CultureInfo.InvariantCulture);
EDIT: my answer above was directed to the code sample in the first version of the question. Now that the question has been edited:
You can control the string representation of your decimal values using the Decimal.ToString(string format, IFormatProvider provider) method overload. This allows you to specify a standard or custom format string. In your case, it sounds like you need to have 2 decimal digits separated using a dot, and no group separators (no commas). So you could say:
price.ToString("F2", CultureInfo.InvariantCulture) // ex. result: "1234.56"
CultureInfo.InvariantCulture is important if you need a dot separator regardless of the current culture. If you don't specify that, the output could be "1234,56" depending on the current culture (e.g. in case of european cultures like de-DE, or fr-FR).
I'm using log4net to output a formatted message. The following code
log.DebugFormat("Balance: {0:c} ", balance);
results in
"Balance: ¤1,000.00"
Why is the odd character appearing and not a $
I would imagine that it is something to do with your regional settings.
Try something like this:
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(<your culture setting>);
log.DebugFormat("Balance: {0:c} ", balance);
If that dosen't work then you can always use the debugger to check the value of:
System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat;
Specifically check the value of:
ansiCurrencySymbol
To ensure that it's set to the '$' symbol.
You may also be intersted in this wikipedia page: http://en.wikipedia.org/wiki/Currency_%28typography%29
Which explains what the symbol you are getting is.
Specifically:
The currency sign (¤) is a character used to denote a currency, when the symbol for a particular currency is unavailable.
It is particularly common in place of symbols, such as that of the Colón (₡), which are absent from most character sets and fonts.
It can be described as a circle the size of a lowercase character with four short radiating arms at 45° (NE), 135° (NW), 225°, (SW) and 315° (SE). It is slightly raised over the baseline.
It is represented in Unicode, as CURRENCY SIGN (U+00A4). In HTML, the character entity reference ¤ or numeric character reference ¤ may be used.
How can I change values in string from 0,00 to 0.00? - only numeric values, not all chars "," to "."
FROM
string myInputString = "<?xml version=\"1.0\"?>\n<List xmlns:Table=\"urn:www.navision.com/Formats/Table\"><Row><HostelMST>12,0000</HostelMST><PublicMST>0,0000</PublicMST><TaxiMST>0,0000</TaxiMST><ParkMST>0,0000</ParkMST><RoadMST>0,0000</RoadMST><FoodMST>0,0000</FoodMST><ErrorCode>0</ErrorCode><ErrorDescription></ErrorDescription></Row></List>\n";
TO
string myInputString = "<?xml version=\"1.0\"?>\n<List xmlns:Table=\"urn:www.navision.com/Formats/Table\"><Row><HostelMST>12.0000</HostelMST><PublicMST>0.0000</PublicMST><TaxiMST>0.0000</TaxiMST><ParkMST>0.0000</ParkMST><RoadMST>0.0000</RoadMST><FoodMST>0.0000</FoodMST><ErrorCode>0</ErrorCode><ErrorDescription></ErrorDescription></Row></List>\n";
Thanks for answers, but I mean to change only numeric values, not all chars "," to "."
I don't want change string from
string = "<Attrib>txt txt, txt</Attrib><Attrib1>12,1223</Attrib1>";
to
string = "<Attrib>txt txt. txt</Attrib><Attrib1>12.1223</Attrib1>";
but this one is ok
string = "<Attrib>txt txt, txt</Attrib><Attrib1>12.1223</Attrib1>";
Try this :
Regex.Replace("attrib1='12,34' attrib2='43,22'", "(\\d),(\\d)", "$1.$2")
output : attrib1='12.34' attrib2='43.22'
The best method depends on the context. Are you parsing the XML? Are you writing the XML. Either way it's all to do with culture.
If you are writing it then I am assuming your culture is set to something which uses commas as decimal seperators and you're not aware of that fact. Firstly go change your culture in Windows settings to something which better fits your culture and the way you do things. Secondly, if you were writing the numbers out for human display then I would leave it as culturally sensative so it will fit whoever is reading it. If it is to be parsed by another machine then you can use the Invariant Culture like so:
12.1223.ToString(CultureInfo.InvariantCulture);
If you are reading (which I assume is what you are doing) then you can use the culture info again. If it was from a human source (e.g. they typed it in a box) then again use their default culture info (default in float.Parse). If it is from a computer then use InvariantCulture again:
float f = float.Parse("12.1223", CultureInfo.InvariantCulture);
Of course, this assumes that the text was written with an invariant culutre. But as you're asking the question it's not (unless you have control over it being written, in which case use InvariantCulture to write it was suggested above). You can then use a specific culture which does understand commas to parse it:
NumberFormatInfo commaNumberFormatInfo = new NumberFormatInfo();
commaNumberFormatInfo.NumberDecimalSeperator = ",";
float f = float.Parse("12,1223", commaNumberFormatInfo);
I strongly recommend joel.neely's regex approach or the one below:
Use XmlReader to read all nodes
Use double.TryParse with the formatter = a NumberFormatInfo that uses a comma as decimal separator, to identify numbers
Use XmlWriter to write a new XML
Use CultureInfo.InvariantCulture to write the numbers on that XML
The answer from ScarletGarden is a start, but you'll need to know the complete context and grammar of "numeric values" in your data.
The problem with the short answer is that cases such as this get modified:
<elem1>quantity<elem2>12,6 of which were broken</elem2></elem1>
Yes, there's probably a typo (missing space after the comma) but human-entered data often has such errors.
If you include more context, you're likely to reduce the false positives. A pattern like
([\s>]-?$?\d+),(\d+[\s<])
(which you can escape to taste for your programming language of choice) would only match when the "digits-comma-digits" portion (with optional sign and currency symbol) was bounded by space or an end of an element. If all of your numeric values are isolated within XML elements, then you'll have an easier time.
string newStr = myInputString.Replace("0,00", "0.00");
While you could theoretically do this using a Regex, the pattern would be complex and hard to to test. ICR is on the right track, you need to do this based on culture.
Do you know that your numbers are always going to be using a comma as a decimal separator instead of a period? It looks like you can, given that Navision is a Danish company.
If so, you'll need to traverse the XML document in the string, and rewrite the numeric values. It appears you can determine this on node name, so this won't be an issue.
When you convert the number, use something similar to this:
here's what you want to do:
internal double ConvertNavisionNumber(string rawValue)
{
double result = 0;
if (double.TryParse(rawValue, NumberStyles.Number, new CultureInfo("da-DK").NumberFormat, out result))
return result;
else
return 0;
}
This tells the TryParse() method that you're converting a number from Danish (da-DK). Once you call the function, you can use ToString() to write the number out in your local format (which I'm assuming is US or Canadian) to get a period for your decimal separator. This will also take into account numbers with different thousands digit separator (1,234.56 in Canada is written as 1 234,56 in Denmark).
ConvertNavisionNumber("4,43").ToString()
will result in "4.43".
ConvertNavisionNumber("1 234").ToString()
will result in "1,234".
if the , is not used anywhere else but number with in the string you can use the following:
string newStr = myInputString.Replace(",", ".");