Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To answer a slightly different question: <em>don't</em> use the float type to represent currency values. <a href="http://www.javapractices.com/topic/TopicAction.do?Id=13" rel="noreferrer">It will bite you</a>. Use a base-10 type instead, like <code>BigDecimal</code>, or an integer type like <code>int</code> or <code>long</code> (representing the quantum of your value - penny, for example, in US currency).</p> <p>You will not be able to store an exact value - 123.45, say, as a float, and mathematical operations on that value (such as multiplication by a tax percentage) will produce rounding errors.</p> <p>Example from that page: </p> <pre><code>float a = 8250325.12f; float b = 4321456.31f; float c = a + b; System.out.println(NumberFormat.getCurrencyInstance().format(c)); // prints $12,571,782.00 (wrong) BigDecimal a1 = new BigDecimal("8250325.12"); BigDecimal b1 = new BigDecimal("4321456.31"); BigDecimal c1 = a1.add(b1); System.out.println(NumberFormat.getCurrencyInstance().format(c1)); // prints $12,571,781.43 (right) </code></pre> <p>You don't want to muck with errors when it comes to money.</p> <p>With respect to the original question, I haven't touched Java in a little while, but I know that I'd like to stay away from regex to do this kind of work. I see this recommended; it may help you. Not tested; caveat developer.</p> <pre><code>try { String string = NumberFormat.getCurrencyInstance(Locale.GERMANY) .format(123.45); Number number = NumberFormat.getCurrencyInstance(locale) .parse("$123.45"); // 123.45 if (number instanceof Long) { // Long value } else { // too large for long - may want to handle as error } } catch (ParseException e) { // handle } </code></pre> <p>Look for a locale with rules that match what you expect to see. If you can't find one, use multiple sequentially, or create your own <a href="http://www.exampledepot.com/egs/java.text/FormatNum.html" rel="noreferrer">custom NumberFormat</a>.</p> <p>I'd also consider forcing users to enter values in a single, canonical format. 123.45 and 123.456 look <em>way</em> too similar for my tastes, and by your rules would result in values that differ by a factor of 1000. <a href="http://blogs.msdn.com/oldnewthing/archive/2009/06/08/9705184.aspx" rel="noreferrer">This is how millions are lost</a>.</p>
 

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