如何在Java中使用带长值的printf()方法?

问题描述 投票:3回答:2

我记得我是用C语言完成的,但是我无法在Java中使用它。

如何在Java中使用printf()方法打印长值?

我尝试使用下面的代码,我真正需要的是以十六进制方式打印long值,如下所示

long l = 32L -----> 0000000000000022

如果我使用%d,那么它将打印我不想要的整数值...

class TestPrintf() 
{
    public static void main(String[] args)
    {

    long l = 100L;

    System.out.printf(“%l”+l); // Error unknown format exception
    System.out.printf(“%d”+l); // Prints 100
    System.out.printf(“%f”+l); // Unknown illegal format conversion float != java.lang.long
    }
}
java printf long-integer
2个回答
2
投票

如果要使用16个字符的零填充字符串,且大写的A-F0x为前缀,则应使用:

System.out.printf("0x%016X", l);

6
投票

您需要将实际参数打印为printf()方法的下一个参数。串联将不起作用。

System.out.printf("%d%n", 123);             // for ints and longs
System.out.printf("%d%n", 12345L);          // for ints and longs
System.out.printf("%f%n", (double) 12345L); // for floating point numbers

java.util.Formatter中的完整文档

© www.soinside.com 2019 - 2024. All rights reserved.