java之實現簡單的傳入一個小數和一個整數,根據傳入的整數,輸出一個有整數位個小數的小數
阿新 • • 發佈:2021-01-15
技術標籤:# JavaSEjava輸出一個想要輸出位數的小數數字格式java之數字格式
java之實現簡單的傳入一個小數和一個整數,根據傳入的整數,輸出一個有整數位個小數的小數
結果如下:
輸入一個小數,和一個想要取多少為位小數的整數
得到:
以下三種方法:
package com.qianfeng.day11;
import sun.nio.cs.ext.MacThai;
import java.text.DecimalFormat;
public class test {
public static void main(String[] args) {
fu (3.5514275,4);
fu1(12.4654,5);
fun2(12.5,1);
}
//第一種:呼叫DecimalFormat類的方法,實現數字格式初始化
public static void fu(Double a, int b) {
String s;
if(b==0) s="0";
else s="0.";
for(int i=0;i<b;i++){
s+=0;
}
DecimalFormat df= new DecimalFormat(s);
System.out.println(df.format(a));
}
//第二種:原生程式碼,不推薦
public static void fu1(double n,int m){
double a = n*Math.pow(10,m);
int b=(int)a;
double c=b/ Math.pow(10,m);
System.out.println(c);
}
//第三種:原生程式碼
public static void fun2( double n,int m){
String num=n+"";
int index=num.indexOf(".");
String a=num.substring(0,index);
String b=num.substring(index+1);
String c="";
if(b.length()>m){
c=b.substring(0,m);
}else if(b.length()<m){
int chaZhi=m-b.length();
for(int i=0;i<chaZhi;i++){
b+="0";
}
c=b;
}else {
System.out.println(num);
return;
}
String str=a+"."+c;
System.out.println(str);
}
}