I\'m having some problems formatting the decimals of a double. If I have a double value, e.g. 4.0, how do I format the decimals so that it\'s 4.00 instead?
I know that this is an old topic, but If you really like to have the period instead of the comma, just save your result as X,00 into a String and then just simply change it for a period so you get the X.00
The simplest way is just to use replace.
String var = "X,00";
String newVar = var.replace(",",".");
The output will be the X.00 you wanted. Also to make it easy you can do it all at one and save it into a double variable:
Double var = Double.parseDouble(("X,00").replace(",",".");
I know that this reply is not useful right now but maybe someone that checks this forum will be looking for a quick solution like this.
An alternative method is use the setMinimumFractionDigits
method from the NumberFormat
class.
Here you basically specify how many numbers you want to appear after the decimal point.
So an input of 4.0
would produce 4.00
, assuming your specified amount was 2.
But, if your Double
input contains more than the amount specified, it will take the minimum amount specified, then add one more digit rounded up/down
For example, 4.15465454
with a minimum amount of 2 specified will produce 4.155
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
Double myVal = 4.15465454;
System.out.println(nf.format(myVal));
Try it online