数字和字符串-字符串转化和格式化输出

数字和字符串-字符串转化和格式化输出

1.字符串转化
1.1数字转字符串
方法1: 使用String类的静态方法valueOf
方法2: 先把基本类型装箱为对象,然后调用对象的toString

package pack6;

public class StringTest {
    public static void main(String args[]){
        int i=2;
        //方法1
        String str=String.valueOf(i);
        //方法2
        Integer it=i;
        String str1=it.toString();
       //判断str是不是String
        System.out.println(str instanceof String);
    }
}

1.2字符串转数字
调用Integer的静态方法parseInt

package pack6;

public class StringTest {
    public static void main(String args[]){
        String s="123";
        int a=Integer.parseInt(s);
    }
}        

1.3练习

把浮点数 3.14 转换为 字符串 “3.14”
再把字符串 “3.14” 转换为 浮点数 3.14
如果字符串是 3.1a4,转换为浮点数会得到什么?

如果字符串是 3.1a4,数字表达式不合法,会有异常抛出,异常:NumberFormatException

package pack6;

public class StringTest {
    public static void main(String args[]){
        double pai=3.14;
        //double转String
        String s1=String.valueOf(pai);

        //String转double
        double pai1=Double.parseDouble(s1);
        }
   }

2.格式化输出
2.1printf和format

package pack6;

public class StringTest {
    public static void main(String args[]){
        //%n是换行
        String sentence="%s今年%d岁了,爱好是%s%n";
        String name="yzs";
        int age=18;
        String hobby="打篮球";
        System.out.format(sentence,name,age,hobby);
        System.out.printf(sentence,name,age,hobby);
    }
}

2.2 总长度,左对齐,补0,千位分隔符,小数点位数,本地化表达

package pack6;

import java.util.Locale;

public class StringTest {
    public static void main(String args[]) {
        int year = 2020;
        //总长度,左对齐,补0,千位分隔符,小数点位数,本地化表达
        //直接打印数字
        System.out.format("%d%n", year);
        //总长度是8,默认右对齐
        System.out.format("%8d%n", year);
        //总长度是8,左对齐
        System.out.format("%-8d%n", year);
        //总长度是4 右补齐
        System.out.format("%-4d0000%n", year);
        //总长度是8,不够补0
        System.out.format("%08d%n", year);
        //千位分隔符
        System.out.format("%,8d%n", year * 10000);
        //小数点位数
        System.out.format("%.2f%n", Math.PI);
        //不同国家的千位分隔符
        System.out.format(Locale.FRANCE, "%,.2f%n", Math.PI * 10000);
        System.out.format(Locale.US, "%,.2f%n", Math.PI * 10000);
        System.out.format(Locale.UK, "%,.2f%n", Math.PI * 10000);
        }
  }      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值