Java division for double and float without E

試著忘記壹切 提交于 2019-12-14 03:25:28

问题


I'm doing some large number divisions (long/long to double, and int/int to float).. But I bump, to a problem when the results include the "E". I know we can use NumberFormat to format when displaying, but that's not what I. Just want the result of the divisions to not involve the "E", i.e. just round it up to the closest float/double that fits in the space.

Anybody got an idea?


回答1:


The internal representation of floating point number does not have a switch for E presence or not (check IEEE-754). So your float/double number is just number (not a number with E or without it).

The only place where you get E is when you print this value out. And while Java uses number formater for printing, so I don't see a point why you don't want to use it here.

System.out.println(new DecimalFormat("#.#####").format(doubleValue)); 



回答2:


The general problem that double and float in binary format. It not always possible to convert decimal fraction to binary fraction. For example 0.2 decmal fraction have infinitely many digits in binary (double) format. So whe converted from bynary format to decimal string, it result something like "0.2000000001" what displayed with E. To solve this problem you can use BigDecimal class what contains number in decimal format, so no E problem - it can easy rounded to any decimal point by setScale method. Or you can sore double as is, an write it to output by String.format("My value are: %.3f", value) - i recommend this way.

If you just want round you value to decimal point you can use:

new BigDecimal(val).setScale(3, RoundingMode.HALF_EVEN).doubleValue()

But there no any garanty what this core return double with fine fraction numbers.



来源:https://stackoverflow.com/questions/9054836/java-division-for-double-and-float-without-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!