There is a class DecimalFormat in Java for the purpose of decimal formatting.
Have a look at the following code:
Have a look at the following code:
import java.text.DecimalFormat; public class ThreeDecimel { public static void main(String[] args) { // TODO Auto-generated method stub String j = "781.5400000"; double i= Double.parseDouble(j); DecimalFormat format = new DecimalFormat("#.###"); System.out.println(format.format(i)); } }But, "#.###" will convert 781.5400000 to 781.54 though we are using 3 decimals after the point. If the requirement is 781.540, we must use the following code fragment, instead of the previous one.
import java.text.DecimalFormat; public class ThreeDecimel { public static void main(String[] args) { // TODO Auto-generated method stub String j = "781.5400000"; i= Double.parseDouble(j); format = new DecimalFormat("0.000"); String a = format.format(i).toString(); System.out.println(a); } }For more information, please refer to the following link: Oracle Documenttaion for DecimalFormatter Happy Learning!!
No comments :
Post a Comment