Note that there are some explanatory texts on larger screens.

plurals
  1. POMethod to parse decimals with various decimal/radix separators
    primarykey
    data
    text
    <p>I do a lot of file parsing, which involves parsing data types like decimal. To help make the code more readable, I've been using the following method:</p> <pre><code>public static decimal? ToDecimal(this string data) { decimal result; if (decimal.TryParse(data, NumberStyles.Integer | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out result)) return result; return null; } </code></pre> <p>This works fine for decimals which are represented with a full-stop/period as the decimal separator. However, I'd like this function to work with other standard decimal separators, particularly the comma. (I read that there is also an Arabic decimal separator: <a href="http://en.wikipedia.org/wiki/Decimal_mark#Other_numeral_systems" rel="nofollow">http://en.wikipedia.org/wiki/Decimal_mark#Other_numeral_systems</a>, but that presumably relies on being able to parse the eastern arabic numerals too). </p> <p>The Culture.CurrentCulture wouldn't be appropriate because the data is not necessarily created on the machine that is doing the processing. So I've now got this:</p> <pre><code>private static CultureInfo CreateCultureWithNumericDecimalSeparator(string separator) { var cultureInfo = (CultureInfo)CultureInfo.InvariantCulture.Clone(); cultureInfo.NumberFormat.NumberDecimalSeparator = separator; return cultureInfo; } private static CultureInfo[] cultureInfos = new CultureInfo[] { CultureInfo.InvariantCulture, CreateCultureWithNumericDecimalSeparator(",") // Normal comma }; public static decimal? ToDecimal(this string data) { foreach (CultureInfo cultureInfo in cultureInfos) { decimal result; if (decimal.TryParse(data, NumberStyles.Integer | NumberStyles.AllowDecimalPoint, cultureInfo, out result)) return result; } return null; } </code></pre> <p>This works, but parsing twice, especially given that TryParse is checking all sorts of settings (thousand separators, hex specifiers, currency symbols, exponents, etc) seems a little heavy. It's probably not a performance issue, but I'm curious to know if there's a more efficient method to do this, or possibly even an existing method within the framework? And maybe even a method that could cope with other numeral systems in modern use? Thanks.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload