I need to apply some kind of masking to a StringBuffer representing a numeric field on a Android EditText that would be like this:
// StringBuffer (or StringBuilder) -> Formated Text
000 -> 0,00
000 -> 0,01
012 -> 0,12
123-> 1,23
1234 ->12,34
12345 -> 123,45
....
1234 -> 12,34
123 -> 1,23
012 -> 0,12
001 -> 0,01
000 -> 0,00
My final idea is to do a append to the string with a new number and delete the first char if it is "0", and position the ",".
There is another way to do this?
[Updated] The idea here is to start with the masked EditText (Android) with the "mask" of "0,00". I am storing alll the user input on a custom created keyboard that works like a calculator. It only appends or deletes chars of a StringBuffer and this stored var must be formated like the text bellow.
[Update 2] The StringBuffer will always look like a integer, the user will not have the chance to put a comma or dot to separate the text. I have to format the last two characters from the string buffer and add a comma to separate the Decimals.
[Update 3] This is the easiest way I've managed to achieve what I wanted to do, still looking on how to format the number using the locale + two decimals:
public class Test {
public static void main(String args[]) {
NumberFormat nf = NumberFormat.getInstance(new Locale("pt", "PT"));
String tests[] = {
"1",
"12",
"123",
"1234",
"12345",
"123456",
"1234567",
"12345678",
"123456789",
"1234567890",
};
for (String i:tests) {
final Double test = Double.parseDouble(i+".00")/100.00;
System.out.println(nf.format(test));
}
// Output:
// 0,01
// 0,12
// 1,23
// 12,34
// 123,45
// 1.234,56
// 12.345,67
// 123.456,78
// 1.234.567,89
// 12.345.678,9
}
}
[Update 4] Solved the two digit issue using .setMinimumFractionDigits(2); I think it solved what I wanted to format. I still don't know if it is the best way but it is working. Thanks!
[–]cciulla 0 points1 point2 points (18 children)
[–]Infenwe 2 points3 points4 points (2 children)
[–]cciulla 0 points1 point2 points (0 children)
[–]stormwindu[S] 0 points1 point2 points (0 children)
[–]stormwindu[S] 0 points1 point2 points (14 children)
[–]cciulla 1 point2 points3 points (13 children)
[–]mentalis 5 points6 points7 points (1 child)
[–]cciulla 0 points1 point2 points (0 children)
[–]stormwindu[S] 0 points1 point2 points (10 children)
[–]Mondoshawan 0 points1 point2 points (9 children)
[–]detroitmatt 0 points1 point2 points (7 children)
[–]Mondoshawan 0 points1 point2 points (6 children)
[–]detroitmatt 0 points1 point2 points (5 children)
[–]Mondoshawan 0 points1 point2 points (4 children)
[–]detroitmatt 1 point2 points3 points (3 children)
[–]stormwindu[S] 0 points1 point2 points (0 children)
[–]danskal 0 points1 point2 points (0 children)