zoukankan      html  css  js  c++  java
  • java中的BigDecimal和String的相互转换,int和String的类型转换,Integer类和String相互转换

    一:

    /*由数字字符串构造BigDecimal的方法
    *设置BigDecimal的小数位数的方法
    */

    注:BigDecimal在数据库中存的是number类型。


    import java.math.BigDecimal;


    //数字字符串
    String StrBd="1048576.1024";


    //构造以字符串内容为值的BigDecimal类型的变量bd
    BigDecimal bd=new BigDecimal(StrBd);


    //设置小数位数,第一个变量是小数位数,第二个变量是取舍方法(四舍五入)
    bd=bd.setScale(2, BigDecimal.ROUND_HALF_UP);


    //转化为字符串输出
    String OutString=bd.toString();

     二:int和String的类型转换

     int -> String

    int i=12345;
    String s="";
    第一种方法:s=i+"";
    第二种方法:s=String.valueOf(i);

    区别:第一种方法:s=i+""; //会产生两个String对象

              第二种方法:s=String.valueOf(i); //直接使用String类的静态方法,只产生一个对象

     String -> int

    s="12345";
    int i;
    第一种方法:i=Integer.parseInt(s);
    第二种方法:i=Integer.valueOf(s).intValue();

    区别:第一种方法:i=Integer.parseInt(s);//直接使用静态方法,不会产生多余的对象,但会抛出异常

              第二种方法:i=Integer.valueOf(s).intValue();//Integer.valueOf(s) 相当于 new Integer(Integer.parseInt(s)),也会抛异常,但会多产生一个对象

    示例:

    1如何将字串 String 转换成整数 int?
    A. 有两个方法:
    1). int i = Integer.parseInt([String]); 或
    i = Integer.parseInt([String],[int radix]);
    2). int i = Integer.valueOf(my_str).intValue();
    注: 字串转成 Double, Float, Long 的方法大同小异.

    2 如何将整数 int 转换成字串 String ?
    A. 有叁种方法:
    1.) String s = String.valueOf(i);

    2.) String s = Integer.toString(i);

    3.) String s = "" + i;

    注: Double, Float, Long 转成字串的方法大同小异.

    三:Integer类和String相互转换

    //方法一:Integer类的静态方法toString()
    Integer a = 2;
    String str = Integer.toString(a)

    //方法二:Integer类的成员方法toString()
    Integer a = 2;
    String str = a.toString();

    //方法三:String类的静态方法valueOf()
    Integer a = 2;
    String str = String.valueOf(a);

    四:Integer 类和 int 的区别

    1)Integer 是 int 包装类,int 是八大基本数据类型之一(byte,char,short,int,long,float,double,boolean)
    2)Integer 是类,默认值为null,int是基本数据类型,默认值为0;
    3)Integer 表示的是对象,用一个引用指向这个对象,而int是基本数据类型,直接存储数值。

  • 相关阅读:
    SpringSecurity________UsernamePasswordAuthenticationFilter
    Spring Security初步学习
    BASE64
    UUID
    Filter-Chain模式简介
    Servlet容器的简单回顾
    java环境搭建的一些小知识
    Restrictions查询用法
    servlet中session的使用
    strust2中使用session
  • 原文地址:https://www.cnblogs.com/js1314/p/10183091.html
Copyright © 2011-2022 走看看