【Java】【30】数据基本类型的转换

前言:

基本类型:Character, Byte, Short, Integer, Long, Float, Double, Boolean.

注:部分精度丢失问题未确认

正文:

1,boolean

boolean类型与其他基本类型不能进行类型的转换,可以用if..else..或者三元表达式转换

2,int

int i = 10;

int 转化成String:

(1)String str = Integer.toString(i);

(2)String str = String.valueOf(i);

(3)String str = i + " ";

int 转化成float:

(1)强制转换 float b  =  (float) i;

(2)i*1.0 或 i/1.0 float b = i*1.0;

int 转化成double:

(1)double a = i;

int 转化成bigdecimal:

(1)BigDecimal number = BigDecimal.valueOf((int) i);

3,String

String str = "123456";

String 转化成int:

(1)int i = Integer.parseInt(str);

(2)int i = Integer.valueOf(str).intValue();

String 转化成float:

(1)float f = Float.parseFloat(str);

String 转化成double:

(1)double d = Double.valueOf(str).doubleValue();

4,float

float f = 0.1f或 float f = (float) 0.1;

float 转化成int:

(1)int i = (int) f;  

float  转化成String:

(1)String str = String.valueOf(a);

(2)String str = a + " ";

float  转化成double:

(1)double d = f;

(2)精度不丢失:

float f = 127.1f;

BigDecimal b = new BigDecimal(String.valueOf(f));

double d = b.doubleValue();

5,double

double d = 10.23;

double 转化成int:

(1)只取整数部分 :int i = (int) d;

(2)int i = (new Double(d)).intValue();

double 转化成String:

(1)String str = Double.toString(d);

(2)String str  = d.ToString("r");

(3)String str = String.valueOf(d);

double 转化成float:

(1)float f = (float)d;

6,备注

1,所有数据类型的可以强制转换,但可能会存在精度丢失的问题

2,BigDecimal可处理精度问题

3,截取一定的位数:

      DecimalFormat decimalFormat = new DecimalFormat("##0.0");
      float Erate = Float.parseFloat(decimalFormat.format(this.DoneQTY * 100.0F / this.PlanQTY));

       ——  decimalFormat.format(this.DoneQTY * 100.0F / this.PlanQTY)为String类型

参考资料

Java:数据类型转换 - 子 孑 - 51CTO技术博客: http://zhangjunhd.blog.51cto.com/113473/17552/

java int short long float double 大整理(不要错过)-hxz_zt-ChinaUnix博客  : http://blog.chinaunix.net/uid-26930580-id-4175110.html

Java中float和double转换的问题?-CSDN论坛-CSDN.NET-中国最大的IT技术社区 : http://bbs.csdn.net/topics/340231509

float转int 四舍五入问题 - 非著名码农的专栏 - 博客频道 - CSDN.NET : http://blog.csdn.net/ropai/article/details/19907847

BigDecimal用法详解 - Ruthless - 博客园 : http://www.cnblogs.com/linjiqin/p/3413894.html

posted @ 2019-06-19 22:01  花生喂龙  阅读(252)  评论(0编辑  收藏  举报