您的位置:首页 > 编程语言 > Java开发

编程之美2.6精确表达浮点数Java版

2016-06-13 18:03 447 查看
程序很简单,还没有约分
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Test;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Scanner;

/**
*
* @author Administrator
*/
public class ShowFloat {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String num = sc.next();
String str = show(num);
System.out.println(str);
}

private static String show(String num) {
String str = "";
String[] arry = num.split("\\.");
String[] arry1 = arry[1].split("\\(");
String finite = arry1[0];
String infinite = "";
if (arry1.length > 1) {
infinite = arry1[1].substring(0, arry1[1].length() - 1);
}
int finite_length = finite.length();
if ("".equals(infinite)) {
//只有有限小数部分
str = finite + "/" + Math.pow(10, finite_length);
} else {
int infinite_length = infinite.length();
BigDecimal b1 = new BigDecimal(Math.pow(10, infinite_length) + "").subtract(new BigDecimal("1"));
BigDecimal b2 = new BigDecimal(finite).multiply(b1);
BigDecimal b3 = b2.add(new BigDecimal(infinite));
BigDecimal b4 = b1.multiply(new BigDecimal(Math.pow(10, finite_length)));
str = b3.toString() + "/" + b4.toString();
}

return str;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: