package org.gwtoolbox.commons.conversion.client.converter;
import com.google.gwt.i18n.client.NumberFormat;
import org.gwtoolbox.commons.types.client.Money;
/**
* @author Uri Boness
*/
public class MoneyTextConverter extends AbstractTextConverter {
private static final String DEFAULT_DECIMAL_SEPARATOR = ".";
private static final String DEFAULT_FORMAT = "#,###";
private final NumberFormat format;
private final String decimalSeparator;
public MoneyTextConverter() {
this(NumberFormat.getFormat(DEFAULT_FORMAT), DEFAULT_DECIMAL_SEPARATOR);
}
public MoneyTextConverter(NumberFormat format, String decimalSeparator) {
this.format = format;
this.decimalSeparator = decimalSeparator;
}
public Class[] getSupportedTypes() {
return new Class[] { Money.class };
}
public String toText(Object value) {
Money money = (Money) value;
StringBuilder builder = new StringBuilder()
.append(format.format(money.getUnitPart()))
.append(decimalSeparator)
.append(padCents(money.getCentPart()))
.append(" ")
.append(money.getCurrency().getCurrencyCode());
return builder.toString();
}
public String toHTML(Object value) {
Money money = (Money) value;
StringBuilder builder = new StringBuilder()
.append(money.getCurrency().getHtmlSymbol())
.append(" ")
.append(format.format(money.getUnitPart()))
.append(decimalSeparator)
.append(padCents(money.getCentPart()));
return builder.toString();
}
// todo: implement this method once, the Currency class is enhanced with a currency registry.
public Object toValue(String text) {
throw new UnsupportedOperationException("MoneyTextConveter is a one-way converter from Money to String");
}
//============================================== Helper Methods ====================================================
private String padCents(int cents) {
if (cents == 0) {
return "00";
}
if (cents < 10) {
return "0" + cents;
}
return String.valueOf(cents);
}
}