Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is an alternative approach, which does not have I18n problems (allowing ',' or '.' but not both): <a href="http://msdn.microsoft.com/library/9zbda557" rel="noreferrer"><code>Decimal.TryParse</code></a>.</p> <p>Just try converting, ignoring the value.</p> <pre><code>bool IsDecimalFormat(string input) { Decimal dummy; return Decimal.TryParse(input, out dummy); } </code></pre> <p>This is significantly faster than using a regular expression, see below.</p> <p>(The overload of <a href="http://msdn.microsoft.com/library/ew0seb73" rel="noreferrer"><code>Decimal.TryParse</code></a> can be used for finer control.)</p> <hr/> <p>Performance test results: Decimal.TryParse: 0.10277ms, Regex: 0.49143ms</p> <p>Code (<code>PerformanceHelper.Run</code> is a helper than runs the delegate for passed iteration count and returns the average <code>TimeSpan</code>.):</p> <pre><code>using System; using System.Text.RegularExpressions; using DotNetUtils.Diagnostics; class Program { static private readonly string[] TestData = new string[] { "10.0", "10,0", "0.1", ".1", "Snafu", new string('x', 10000), new string('2', 10000), new string('0', 10000) }; static void Main(string[] args) { Action parser = () =&gt; { int n = TestData.Length; int count = 0; for (int i = 0; i &lt; n; ++i) { decimal dummy; count += Decimal.TryParse(TestData[i], out dummy) ? 1 : 0; } }; Regex decimalRegex = new Regex(@"^[0-9]([\.\,][0-9]{1,3})?$"); Action regex = () =&gt; { int n = TestData.Length; int count = 0; for (int i = 0; i &lt; n; ++i) { count += decimalRegex.IsMatch(TestData[i]) ? 1 : 0; } }; var paserTotal = 0.0; var regexTotal = 0.0; var runCount = 10; for (int run = 1; run &lt;= runCount; ++run) { var parserTime = PerformanceHelper.Run(10000, parser); var regexTime = PerformanceHelper.Run(10000, regex); Console.WriteLine("Run #{2}: Decimal.TryParse: {0}ms, Regex: {1}ms", parserTime.TotalMilliseconds, regexTime.TotalMilliseconds, run); paserTotal += parserTime.TotalMilliseconds; regexTotal += regexTime.TotalMilliseconds; } Console.WriteLine("Overall averages: Decimal.TryParse: {0}ms, Regex: {1}ms", paserTotal/runCount, regexTotal/runCount); } } </code></pre>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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