java小数加法

Python017

java小数加法,第1张

System.out.printf("%.2f\n",0.9+0.9+0.1+0.5)//用类似c语言的格式输出

System.out.format("%.2f\n", 0.9+0.9+0.1+0.5)//java.util.Formatter包中的format方法格式输出

System.out.format("%1$.2f", 0.9+0.9+0.1+0.5)//1$代表第一个参数.2f代表精确到小数点后2位

2.40

2.40

2.40

程序输出结果均为2.40

建议多查API

按照你的要求为不确定保留几位小数的字符串做四舍五入的Java程序如下

import java.math.BigDecimal

public class A {

public static void main(String[] args) {

String s="0.00000999999997"

//四舍五入,length是小数位数

int length=s.substring(s.indexOf(".")+1).length()

String s1=String.format("%."+(length-1)+"f",new BigDecimal(s))

//去尾部0

BigDecimal bd=new BigDecimal(s1).stripTrailingZeros()

System.out.println(bd.toPlainString())

}

}