Boa Tarde!!
Estou usando o código abaixo que encontrei na net para formatar o valor monetário na minha aplicação.
O problema está quando salva:
Digito: 1.000,00
Salva no banco: 0.010.000,00
[code]package br.com.util;
import javax.swing.text.*;
public class Moeda extends PlainDocument {
private static final long serialVersionUID = 1L;
public static final int NUMERO_DIGITOS_MAXIMO = 12;
@SuppressWarnings(“static-access”)
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
String texto = getText(0, getLength());
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (!Character.isDigit©) {
return;
}
}
if(texto.length() < this.NUMERO_DIGITOS_MAXIMO){
super.remove(0, getLength());
texto = texto.replace(".", “”).replace(",", “”);
StringBuffer s = new StringBuffer(texto + str);
if (s.length() > 0 && s.charAt(0) == ‘0’) {
s.deleteCharAt(0);
}
//Acho que o problema está aqui porque coloca os zeros à esquerda
if(s.length() < 3) {
if (s.length() < 1) {
s.insert(0,“000”);
}else if (s.length() < 2) {
s.insert(0,“00”);
}else{
s.insert(0,“0”);
}
}
s.insert(s.length()-2, “.”);
if(s.length() > 6) {
s.insert(s.length()-6, “.”);
}
if(s.length() > 10) {
s.insert(s.length()-10, “.”);
}
super.insertString(0, s.toString(), a);
}
}
public void remove(int offset, int length) throws BadLocationException {
super.remove(offset, length);
String texto = getText(0, getLength());
texto = texto.replace(",", “.”);
texto = texto.replace(".", “”);
super.remove(0, getLength());
insertString(0, texto, null);
}
}
[/code]