例如:public String round(double v,int num){
}
v是要计算的数,num是保留的位数
例如传:12.123,2 则返回12.12 传12 则返回12
传12.123,3 则返回12.123 谢谢!
------解决方案--------------------
我有个方法,可以--> String在通过(好象是你回去看一下)indexOf()查找 ". "
若返回的不是-1
再用subString()方法截取 ". "以后你要的长度
------解决方案--------------------
public String round(double v,int num){
String value= " "+v;
int index=value.indexOf( ". ");
if(index!=-1){
if(num+index <=value.length())
{
String getString=value.subString(0,num+index+1);
return getString;
}
}
return value;
}
------解决方案--------------------
public String round(double v,int num){
String fmt = "0000000000000000 ";//16位
fmt = num> 0? "0. "+fmt.substring(0,num): "0 ";
DecimalFormat df = new DecimalFormat(fmt);
return(df.format(v));
}
------解决方案--------------------
根据楼主的要求,写了一个,测试没有问题,楼主结贴吧
import java.text.*;
public class DoubleFormat
{
public static void main(String[]args)
{
DoubleFormat t = new DoubleFormat();
System.out.print(t.doubleOutPut(12.369,2));
}
public String doubleOutPut(double v,Integer num)
{
if (v == Double.valueOf(v).intValue())
return Double.valueOf(v).intValue()+ " ";
else
{
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
return formatter.format(v);
}
}
}
------解决方案--------------------
上面的不是有个变量没有代进去.
这下好了.
import java.text.*;
public class DoubleFormat
{
public static void main(String[]args)
{
DoubleFormat t = new DoubleFormat();
System.out.print(t.doubleOutPut(12.369,2));
}
public String doubleOutPut(double v,Integer num)
{
if (v == Double.valueOf(v).intValue())
return Double.valueOf(v).intValue()+ " ";
else
{
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMaximumFractionDigits(num);
formatter.setMinimumFractionDigits(num);
return formatter.format(v);
}
}
}
------解决方案--------------------
楼上方法都不错 LZ可以结贴了
------解决方案--------------------
public class Test {
public static void main(String[] args) {
Test t = new Test();
System.out.print(t.round(12.345, 2));
}
public String round(double v, int num) {
String multipliedValue = Math.round(v * Math.pow(10, num)) + " ";
String outputValue = multipliedValue.substring(0
, multipliedValue.length() - num) ;
outputValue += ". ";
outputValue += multipliedValue.substring(outputValue.length() - 1
,multipliedValue.length());
return outputValue;
}
}
------解决方案--------------------