Java小数点
我的问题是: 如何让程序打印小数点前的位数和数字后的位数Java小数点,java,decimal,point,Java,Decimal,Point,我的问题是: 如何让程序打印小数点前的位数和数字后的位数 public class Strings { public static void main(String args[]) { double number = 17.0/3; DecimalFormat number_format = new DecimalFormat("#.###"); System.out.println(number); String formatted_string = numb
public class Strings {
public static void main(String args[])
{
double number = 17.0/3;
DecimalFormat number_format = new DecimalFormat("#.###");
System.out.println(number);
String formatted_string = number_format.format(number);
System.out.println(formatted_string);
}
}
我需要小数点前的整数数
我需要得到1和3的结果。小数点前的位数-
十进制格式#setMaximumIntegraterDigits
它完成了这项工作-
double number = (double)17/3;
java.text.DecimalFormat number_format = new java.text.DecimalFormat("#.###");
number_format.setMaximumIntegerDigits(0);
System.out.println(number);
String formatted_string = number_format.format(number);
System.out.println(formatted_string);
结果:
5.666666 7.667
最简单的方法是将数字转换为字符串,然后根据“.”分隔符拆分字符串。然后用“”拆分第一个数组元素。这个数组的长度将为您提供答案
// number = some_number.some_more_numbers;
String value = number + ""; // convert to string
String[] parts = value.split(".");
String[] numbers = parts[0].split("");
int length = numbers.length; // Gives number of individual numbers before decimal point
我希望这能有所帮助。或者更简单的方法
double d = 17.0/3;
System.out.format("%1.2f", d);
试试这个
double d = 15.0/4; // Assuming a number
String ds = String.valueOf(d); // converting it into string (it will be 3.75)
String arr[] = ds.split("\\D"); // splitting by non number charecter (in our case its dot)
// So array containts ["3", "75"] strings
System.out.println("Before Decimal point: "+ arr[0].length()); // length gives number of digits
System.out.println("After Decimal point: "+ arr[1].length());
顺便说一句,17/3=5也许你的意思是17.0/3,也就是5.66666,你得到了什么结果?我想我需要小数点前的位数,所以在这种情况下,它应该打印1和3。