栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

Java | 字符串与数字的转换

Java 更新时间:发布时间: 百科书网 趣学号
一、字符串 转 数字

        1. 通过 parse 方法

public class StringToFigure {
    public static void main(String[] args) {
        String s = "12.35";

        float y1 = Float.parseFloat(s);
        System.out.printf("%fn", y1);
        double y2 = Double.parseDouble(s);
        System.out.printf("%fn", y2);
    }
}

        2. 通过 valueOf 方法

public class StringToFigure {
    public static void main(String[] args) {
        String s = "12.35";

        float y3 = Float.valueOf(s).floatValue();
        System.out.printf("%fn", y3);
        double y4 = Double.valueOf(s).doubleValue();
        System.out.printf("%fn", y4);
    }
}

二、数字 转 字符串

        1. 通过 toString 方法

public class FigureToString {
    public static void main(String[] args){
        int i = 1234;
        float f = 12.34f;
        double d = 123.4;

        String s1 = Integer.toString(i);
        String s2 = Float.toString(f);
        String s3 = Double.toString(d);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
    }
}

        2. 通过 String 类的 valueOf 方法

public class FigureToString {
    public static void main(String[] args){
        int i = 1234;
        float f = 12.34f;
        double d = 123.4;

        String s4 = String.valueOf(i);
        String s5 = String.valueOf(f);
        String s6 = String.valueOf(d);
        System.out.println(s4);
        System.out.println(s5);
        System.out.println(s6);
    }
}
转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/986287.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号