001
002 /*****************************************************************************
003
004 jBudget.
005 Copyright (C) 2006 Dmitri Petrov
006
007 This program is free software: you can redistribute it and/or modify
008 it under the terms of the GNU General Public License as published by
009 the Free Software Foundation, either version 3 of the License, or
010 (at your option) any later version.
011
012 This program is distributed in the hope that it will be useful,
013 but WITHOUT ANY WARRANTY; without even the implied warranty of
014 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
015 GNU General Public License for more details.
016
017 You should have received a copy of the GNU General Public License
018 along with this program. If not, see <http://www.gnu.org/licenses/>.
019
020 *****************************************************************************/
021
022 /*
023 * CurrencyFormater.java
024 *
025 * Created on May 4, 2006, 6:08 PM
026 */
027
028 package org.jbudget.util;
029
030 import java.text.NumberFormat;
031 import java.text.ParseException;
032 import org.jbudget.io.DataManager;
033
034 /**
035 * Formats and parses amount of money to/from long values used as
036 * internal representation.
037 *
038 * @author petrov
039 */
040 public class CurrencyFormater
041 {
042 private static final NumberFormat formater =
043 NumberFormat.getCurrencyInstance(
044 DataManager.getInstance()
045 .getSharedPreferences()
046 .getLocale());
047
048 /** Currency symbol */
049 private static final String currencySymbol =
050 DataManager.getInstance()
051 .getSharedPreferences()
052 .getCurrency()
053 .getSymbol();
054
055 /** Expression Parser */
056 private static final ExpressionParser exprParser = new ExpressionParser();
057
058 /**
059 * Creates a new instance of CurrencyFormater
060 */
061 private CurrencyFormater(){}
062
063 /** Returns a string representation of the amount */
064 public static String format(long amount)
065 {
066 String amountStr;
067 synchronized (formater){
068 if (amount < 0)
069 amountStr = "-" + formater.format(-amount/100.0);
070 else
071 amountStr = formater.format(amount/100.0);
072 }
073 return amountStr;
074 }
075
076 /** Parses a string into amount */
077 public static long parse(String amountStr) throws ParseException
078 {
079 while (amountStr.startsWith(" "))
080 amountStr = amountStr.substring(1);
081 int sign = 1;
082 if (amountStr.startsWith("-")){
083 sign = -1;
084 amountStr = amountStr.substring(1);
085 }
086 if (!amountStr.startsWith(currencySymbol))
087 amountStr = currencySymbol + amountStr;
088
089 float fAmount = 100 * NumberFormat.getCurrencyInstance().parse(
090 amountStr).floatValue();
091 fAmount = Math.round(fAmount);
092
093 return sign * (long)(fAmount);
094 }
095
096 /** Parses a string containing a math expression into amount */
097 public static long parseExpression(String exprString) throws ParseException
098 {
099 return exprParser.parse(exprString);
100 }
101
102 }