Use this
public float decimalDigits(int decimaldigits, float x){
final NumberFormat numFormat = NumberFormat.getNumberInstance();
numFormat.setMaximumFractionDigits(decimaldigits);
final String resultS = numFormat.format(x);
String parsable=resultS.replace(".", "");
parsable=resultS.replace(",", ".");
float ris=Float.parseFloat(parsable);
return ris;
}
I have added the String replacement to the code to avoid Parsing issue caused by the dot convention (for example 1234.34 becomes 1.234,34 after the formatting causing error in reparsing in float)
If the your is simply a format visualization problem, you could also use the String and doesn't matter that floating point variables don't have decimal places, so this is another valid method:
public String decimalDigits(int decimaldigits, float x){
final NumberFormat numFormat = NumberFormat.getNumberInstance();
numFormat.setMaximumFractionDigits(decimaldigits);
final String resultS = numFormat.format(x);
return resultS;
}
If someone has doubts about validity of this solution, should ask for details or try to compile the code and test it before downvote, thanks. The code is tested and works like a charm.
WARNING
Clearly you have to pass float because the method use Float.parseFloat, if you want to pass a double you have to use a cast to float before pass it in the method, otherwise you have to change all the method primitive and parse from float to double. Double and float are different.