我想在两个精度中转换双精度值。假设double s = 1.3333333和它的答案是这样的s = 1.33
这是使用java.text.DecimalFormat在java中完成的。
double s = 1.4454644567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(d));但不是在黑莓。
发布于 2012-01-17 15:39:02
你可以通过这段代码:
Formatter format=new Formatter();
double d1=Double.parseDouble(format.formatNumber(1.33333, 2));
double d2=Double.parseDouble(format.formatNumber(10.487586, 3));
double d3=Double.parseDouble(format.formatNumber(10.487586, 5));
System.out.println("=================: "+d1+"======"+d2+"==========="+d3);我在控制台中的输出是:
=================:1.33======10.487===========10.48758
这里“2”、“3”和“5”表示点(.)后所需的小数位数;
发布于 2012-01-17 20:58:37
如果你想手工做这件事,这可能对你有帮助
public static String roundDouble(String s, int presicion){
int initialPos = s.indexOf('.');
String result = s;
String pre;
String pos;
if (initialPos != -1){
pre = s.substring(0, initialPos);
pos = s.substring(initialPos + 1, s.length());
if (presicion < pos.length()){
pos = s.substring(initialPos + 1, initialPos + 1 + presicion );
int dec = Integer.parseInt(pos);
int next = Integer.parseInt(s.substring(initialPos + 1 + presicion, initialPos + 2 + presicion )); //to round the las digit
if (next > 4){
dec = dec + 1;
pos = dec + "";
if ((dec+"").length() > presicion){
pre = (Integer.parseInt(pre) + 1) + "";
pos = "0";
}
}
} else {
}
result = pre + "." + pos;
}
return result;
}发布于 2012-01-17 21:02:20
你可以使用这个
public static String roundTwoDecimal(String num) {
// Turn random double into a clean currency format (ie 2 decimal places)
StringBuffer result;
double numValue = Double.parseDouble(num);
if (Math.abs(numValue) < .01) {
result = new StringBuffer("0.00");
} else {
if (numValue > 0)
numValue = numValue + 0.005;
else
numValue = numValue - 0.005;
result = new StringBuffer(Double.toString(numValue));
final int point = result.toString().indexOf('.');
if (point > 0) {
// If has a decimal point, may need to clip off after 2 decimal
// places
if (point < (result.length() - 2)) {
// eg "3.1415"
result = new StringBuffer(result.toString().substring(0,
point + 3));
}
}
}
return result.toString();
}https://stackoverflow.com/questions/8890164
复制相似问题