Reputation: 9322
I want to format a number in Android
(or Java
for that matter) say
12345.67
to
12,345.67
But that it will work with lower API level, namely, from API level 15 and up.
I tried NumberFormat NumberFormat.getInstance().format(myNumber)
or NumberFormat.getCurrencyInstance().format(myNumber)
to no avail. Also I tried DecimalFormat without success also, that is, it will give you a warning Call requires API level 24 (current min is 15)
which basically means that although my code will work with phone running on API level 24 but not with older version of Android that uses at least API level 15.
So, what would be my recourse? I don't want to use by the way a utility function just for this but preferably a method from a library. Also System.out.format()
is out of the question, since I want to show it using Toast
.
Upvotes: 3
Views: 2198
Reputation: 1985
Hey I have used this code it works on API 17(4.2.2).So i think it should work on API 15 and above.
public static String Round(String Rval, int Rpl) {
DecimalFormat df = null ;//("#.00");
String finalStr = "";
if(Rval.contains(".")){
String [] inputArr = Rval.split("\\.");
String newValue = "";
/*if(inputArr[1].length() == 1){
inputArr[1] = inputArr[1] + "0";
}else if(inputArr[1].length() >= 2){
inputArr[1] = inputArr[1].substring(0,2);
//inputArr[1] = String.valueOf(Math.round(Integer.parseInt(inputArr[1])));
}*/
int length = inputArr[0].length();
if(length == 7){
df = new DecimalFormat("#,###,###.00");
newValue = df.format(Double.parseDouble(Rval));
}else if(length == 8){
df = new DecimalFormat("#,##,##,###.00");
newValue = df.format(Double.parseDouble(Rval));
}else if(length == 9){
df = new DecimalFormat("##,##,##,###.00");
newValue = df.format(Double.parseDouble(Rval));
}else if(length == 6){
df = new DecimalFormat("###,###.00");
newValue = df.format(Double.parseDouble(Rval));
}else if(length == 5){
df = new DecimalFormat("##,###.00");
newValue = df.format(Double.parseDouble(Rval));
}else if(length == 4){
df = new DecimalFormat("#,###.00");
newValue = df.format(Double.parseDouble(Rval));
}else{
df = new DecimalFormat("#0.00");
newValue = df.format(Double.parseDouble(Rval));
}
finalStr = newValue ;//+"."+ inputArr[1];
}else{
finalStr = Rval + ".00";
}
return finalStr;
}
I have checked on my device right now.
Upvotes: 0
Reputation: 31
Use DecimalFormat
from java.text
to work on Minimum API
below 21
#import java.text
....
double num = 123456.78;
String newValue = new DecimalFormat("##.##").format(num);
Upvotes: 3
Reputation: 9322
Wow, I thought it was something that I have to make a special utility function.
It was simply a String.format()
method did the trick.
Double num = 12345.67;
String formatted = String.format("%,.2f", num);
Upvotes: 3