简体   繁体   English

如何在Java中将零的char数组转换为int

[英]How to convert a char array with zero to int in java

I have a char array that starts with zeroes, but when I try to convert it to a int value, it deletes the zeroes, so I want to keep the zeroes as well. 我有一个以零开头的char数组,但是当我尝试将其转换为int值时,它会删除零,因此我也想保留零。

Something like this array char contains 00001234 and the int has to be like this 00001234 , but when I use the parseInt it just leaves me 1234. 像这样的数组char包含00001234,并且int必须像这样00001234 ,但是当我使用parseInt它只剩下1234。

An int contains a pure numeric value; 一个int包含一个纯数字值; there's no notion of representation like leading zeroes, thousands separators, etc. Anything like that is considered formatting -- it's only relevant when you need to display your int or convert it to text somehow. 没有像前导零,千位分隔符之类的表示形式的概念。任何类似的形式都被视为格式设置 -仅在需要显示int或以某种方式将其转换为文本时才有意义。 Facilities like NumberFormat or System.out.printf() give you some control over what formatting is applied, so that's what you'll have to use. 诸如NumberFormatSystem.out.printf()使您可以控制所应用的格式,因此必须使用它。

如果要在打印时保持前导零,则可能需要使用Java NumberFormat

You cannot capture leading zeros in an int, or any numeric type. 您不能以int或任何数字类型捕获前导零。 Leading zeros are irrelevant to the internal representation of a number, and are only useful when you're eg printing the number. 前导零与数字的内部表示形式无关,并且仅在例如打印数字时才有用。

When you output the number, instead of printing an int , use a NumberFormat , or a format String with System.out.format / System.out.printf . 输出数字时,不要打印int ,而应使用NumberFormat或具有System.out.format / System.out.printf的格式String

If you must keep the number just as it was input, or as it is in your char[] , with the same number of leading zeros, you'll need to keep it around as a char[] , while doing numeric computations with the numeric equivalent from eg parseInt . 如果您必须保持输入的数字不变或char[]的数字不变,且前导零个数相同,则在使用数字进行数值计算时,需要将其保持为char[]左右。等价于parseInt数值。

int不知道数字的格式,无论数字显示在哪里,都必须添加填充

You can't keep formatting stored in a simple int. 您不能将格式存储在简单的int中。 You just store the actual int number and then when you go to display it you use something like NumberFormat to pad it as desired. 您只需要存储实际的int编号,然后在显示它时就可以使用NumberFormat之类的东西来填充它。

000001234 and 1234 are the same as integers. 000001234和1234与整数相同。 What you are looking for is the way to format (display the number) properly the integer and convert it to a string. 您要寻找的是正确格式化(显示数字)整数并将其转换为字符串的方法。

看看是否有帮助,它对如何打印带有前导零的数字有一些建议,如果您可以告诉这些数字的用法,那么可以给出一个更相关的答案...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM