Java transform format String
•
Java
I'm still a novice in Java. I wonder if there is any way to format double without rounding?
double n = 0.12876543;
String s = String.format("%1$1.2f",n);
If I print to the system, it will return 0.13 instead of the exact 0.12 Now I think of a solution, but I wonder if there is a better way to do it This is my simple solution
double n = 0.12876543;
double n = Double.parseDouble(String.format(("%1$1.2f",n));
Any other ideas or solutions?
Solution
An elegant solution is to use setroundingmode with decimal format It sets the roundingmode appropriately
For example:
// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Print statement
System.out.println(curDf.format(n));
Output:
0.12
In addition, if you want to set another format to a string, you can always change the double value to a string:
// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Convert to string for any additional formatting
String curString = String.valueOf(curDf.format(n));
// Print statement
System.out.println(curString);
Output:
0.12
Please refer to similar solutions here: https://stackoverflow.com/a/8560708/4085019
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
