Author: bpoussin Date: 2012-08-22 08:09:40 +0200 (Wed, 22 Aug 2012) New Revision: 1498 Url: http://nuiton.org/repositories/revision/wikitty/1498 Log: meilleur parsing des NUMBER (BigDecimal) Modified: trunk/wikitty-api/src/main/java/org/nuiton/wikitty/WikittyUtil.java Modified: trunk/wikitty-api/src/main/java/org/nuiton/wikitty/WikittyUtil.java =================================================================== --- trunk/wikitty-api/src/main/java/org/nuiton/wikitty/WikittyUtil.java 2012-08-15 17:48:49 UTC (rev 1497) +++ trunk/wikitty-api/src/main/java/org/nuiton/wikitty/WikittyUtil.java 2012-08-22 06:09:40 UTC (rev 1498) @@ -48,6 +48,8 @@ import java.net.InetAddress; import java.net.NetworkInterface; import java.security.Key; +import java.text.DecimalFormat; +import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -141,6 +143,9 @@ "yyyy-MM-dd", "yyyy-MM-dd hh:mm", }; + + /** no break space, used to parse BigDecimal */ + static final public String nbsp = new String(new int[]{160}, 0, 1); // /** All date format parser used to convert string to date */ // static final protected DateFormat[] parserDateFormats = new DateFormat[] { @@ -545,12 +550,39 @@ } else if (value instanceof BigDecimal) { result = (BigDecimal) value; } else { + String s = value.toString(); + // suppression de tous les blancs pour un parsing plus sur + s = StringUtils.deleteWhitespace(s); + s = StringUtils.remove(s, nbsp); try { - result = new BigDecimal(value.toString()); + // on commence par essayer par la methode la plus simple + result = new BigDecimal(s); } catch (NumberFormatException eee) { - throw new WikittyException( - String.format("Can't convert value '%s' to numeric", - getClass(value)), eee); + // on essaie avec un parse, en dernier ressort + // si jamais le nombre etait localise (ex: 99,987.76) + try { + DecimalFormat parser = new DecimalFormat(); + // on veut des BigDecimal en resultat et pas un Double + parser.setParseBigDecimal(true); + + Number n = parser.parse(s); + // meme si on demande au parser un BigDecimal, il retourne + // certaine fois un Double (NaN, Infinit, ...). + // mais dans ce cas la, ca revient a une erreur de parsing + // qui explosera avec le cast + result = (BigDecimal)n; + } catch (Exception zzz) { + // on fait suivre eee et non pas zzz car l'erreur initial + // est bien eee, zzz est juste le fallback, et certain fois + // on aurait un ClassCastException qui n'a rien a voir, + // mais on log tout de meme zzz + log.debug(String.format( + "Can't convert value '%s(%s)' to numeric, this exception is not throw but just logged", + value, getClass(value)), zzz); + throw new WikittyException( + String.format("Can't convert value '%s(%s)' to numeric", + value, getClass(value)), eee); + } } } return result.stripTrailingZeros();
participants (1)
-
bpoussin@users.nuiton.org