Java tutorial
//package com.java2s; /* * Copyright (c) 2011 Denis Solonenko. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v2.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html */ import android.util.Log; import java.math.BigDecimal; import java.text.NumberFormat; import java.text.ParseException; import java.util.regex.Pattern; public class Main { private static final Pattern MONEY_PREFIX_PATTERN = Pattern.compile("\\D"); /** * Adopted from http://jgnash.svn.sourceforge.net/viewvc/jgnash/jgnash2/trunk/src/jgnash/imports/qif/QifUtils.java */ public static BigDecimal parseMoney(String money) { String sMoney = money; if (sMoney != null) { sMoney = sMoney.trim(); // to be safe try { return new BigDecimal(sMoney); } catch (NumberFormatException e) { /* there must be commas, etc in the number. Need to look for them * and remove them first, and then try BigDecimal again. If that * fails, then give up and use NumberFormat and scale it down * */ String[] split = MONEY_PREFIX_PATTERN.split(sMoney); if (split.length >= 2) { StringBuilder buf = new StringBuilder(); if (sMoney.startsWith("-")) { buf.append('-'); } for (int i = 0; i < split.length - 1; i++) { buf.append(split[i]); } buf.append('.'); buf.append(split[split.length - 1]); try { return new BigDecimal(buf.toString()); } catch (final NumberFormatException e2) { Log.e("QifUtils", "Second parse attempt failed, falling back to rounding"); } } NumberFormat formatter = NumberFormat.getNumberInstance(); try { Number num = formatter.parse(sMoney); return new BigDecimal(num.floatValue()); } catch (ParseException ignored) { } Log.e("QifUtils", "Could not parse money " + sMoney); } } return new BigDecimal(0); } }