美文网首页
类型转换截尾与舍入

类型转换截尾与舍入

作者: 小贱嘎嘎 | 来源:发表于2017-06-09 17:42 被阅读0次

如果将一个浮点数转化为整数的话,Java会如何处理呢

public class T {

public static void main(String [] args){
    float fa = 0.4f;
    float fb = 0.7f;
    
    double da = 0.4;
    double db = 0.7;
    
    System.out.println("Float to int below:"+(int)fa);
    System.out.println("Float to int above:"+(int)fb);
    System.out.println("Double to int below:"+(int)da);
    System.out.println("Double to int above:"+(int)db);
}

}

输出结果

Float to int below:0
Float to int above:0
Double to int below:0
Double to int above:0

这里可以看出不论是float还是double,在转化为int时会被截尾(小数点后面的都被截断),那么要怎么才能得到四舍五入的结果呢?这就得用到Math.round()方法了

public class T {

public static void main(String [] args){
    float fa = 0.4f;
    float fb = 0.7f;
    
    double da = 0.4;
    double db = 0.7;
    
    System.out.println("Float to int below:"+Math.round(fa));
    System.out.println("Float to int above:"+Math.round(fb));
    System.out.println("Double to int below:"+Math.round(da));
    System.out.println("Double to int above:"+Math.round(db));
}

}

输出结果

Float to int below:0
Float to int above:1
Double to int below:0
Double to int above:1

相关文章

  • 类型转换截尾与舍入

    如果将一个浮点数转化为整数的话,Java会如何处理呢 输出结果 这里可以看出不论是float还是double,在转...

  • 2019-02-16

    2019-02-1612.5数值取舍函数INT:取整函数,将数字向下舍入为最接近的整数TRUNC:将数字直接截尾取...

  • 类型转换

    字符串与各种类型转换 数字跟各种类型转换 Boolean 类型跟各种类型转换 转换成数值类型 Number(a) ...

  • Swift中Double类型数据的Rounded函数

    Swift中Double类型数据有个Rounded函数,用于对小数进行舍入操作,舍入规则是可以自定义的:

  • Integer源码分析——下(jdk11)

    Integer与原生类型转换 Integer提供了几个与原生类型转换的方法: 由上面的源码可知,Integer类型...

  • Swift 里容易被忽略的类型转换工具

    Swift 类型转换 整数类型之间的转换 实例代码如下: 相比numericCast与使用整数类型的构造方法来转换...

  • iOS-类型转换

    数据类型与char*类型的相互转换(NSData <-> char *) 字符串类型与数据类型的相互转换(NSSt...

  • 2.Java类型转换与数据运算

    类型转换与数据运算 类型转换 自动类型转换 类型范围小的变量,可以直接赋值给类型大的变量 类型:自顶向下为从大到小...

  • java基础篇二(数据类型)

    一、分类: 二、数据类型的转换: 自动类型转换: boolean类型不可能与其他任何数据类型进行转换,整数与浮点数...

  • Swift 类型转换 (as as! as? 区别)

    Swift 语言中类型转换使用的关键字是as,与类型检查相似,Swift语言中的类型转换有向上兼容向下转换之分,也...

网友评论

      本文标题:类型转换截尾与舍入

      本文链接:https://www.haomeiwen.com/subject/eoefqxtx.html