编程之美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; } }
相关文章推荐
- Eclipse Myeclipse 设定文件的默认打开方式
- spring 时间格式化注解@DateTimeFormat @JsonFormat
- java8中switch(String)的错误解决
- JAVA相关博客
- 主动获取spring容器工具类SpringContextUtil
- eclipse老版本加入新SDK后出现问题
- javacv开发详解之1:调用本机摄像头视频(建议使用javaCV1.3.3版本)
- Java List<>排序——重载Collections.sort方法
- 把eclipse工程迁移到Android studio,build成功但run时报butterknife的错,error: duplicate class: class_name$$View(类重复)
- java的一些知识(六)
- red服务在Eclipse中配置
- java中用FileDialog打开文件并将内容添加到文本
- java对象转json
- java 快速排序
- 【原创】增强版冒泡排序算法-java版
- SpringBoot之Hypermedia-Driven RESTful Web Service
- java多线程
- Java语言特性备忘
- Java.util.Enumeration接口
- java的一些知识(五)