简体   繁体   English

在Java中使用浮点型或双精度输出十进制数(Eclipse)

[英]Using float type or double output a decimal number in Java(eclipse)

码

I wanted the output to be 0.123456789123456789 . 我希望输出为0.123456789123456789 But, result is 0.123456789 in float type. 但是,结果是浮点型的0.123456789 0.12345678912345678 in double type. 双重类型为0.12345678912345678 So, I tried using %030.19f,e but this doesn't work either. 因此,我尝试使用%030.19f,e但这也不起作用。 How do I output 0.123456789123456789 ? 我如何输出0.123456789123456789

For bigger numbers you can use BigDecimal. 对于更大的数字,您可以使用BigDecimal。 For example: 例如:

import java.math.BigDecimal;

public class HelloWorld{

 public static void main(String []args){
    BigDecimal bdcm=new BigDecimal("0.123456789123456789");
    System.out.println(bdcm);
    BigDecimal bdcm2=new BigDecimal("100.123456789123456789");
    System.out.println(bdcm.add(bdcm2));
 }
}

And the output is proper :) 和输出是正确的:)

Don't use float or double if you need to print exact values. 如果需要打印精确值,请不要使用floatdouble

Use instead a BigDecimal that is a class to hold 改用BigDecimal作为类来保存

Immutable, arbitrary-precision signed decimal numbers 不可变, 任意精度的带符号十进制数字

The problem using float and double is that they suffer for the rounding related to binary decimal numbers. 使用floatdouble的问题在于它们会遭受与二进制十进制数字有关的舍入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在JAVA中,可以使用大十进制浮点数和双数减去 - In JAVA, can float and double number subtracted by using big decimal 如何在Java中识别数字是浮点型还是双精度型 - how to identify if a number is of float or double type in java Java:如果小数为0,如何将双类型数输出为整数格式 - Java: how to output double-type number to integer format if its decimal is 0 在Java中将十六进制double / float转换为Decimal double / float - Converting Hex double/float to Decimal double/float in Java 显式类型转换vs使用后缀为float / double Java - 区别? - Explicit type casting vs using suffix for float/double Java - difference? 如果float是整数(java),将小数位数设置为0? - Set number of decimal places to 0 if float is an integer (java)? 在Java中定义双精度数的小数位 - defining decimal places of a double number in Java 在 Java 中,如何在输出 double 是整数时删除它的小数位,但在它是浮点数时保留它们? - In Java, how do I remove the decimal places of an output double when it's an integer but keep them when it's a float? Java:将float转换为保留双精度小数点的精度 - Java: convert float to double preserving decimal point precision 为什么Java会在这种情况下将double类型转换为float类型? - Why will Java convert the double to float type in this situation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM