简体   繁体   English

如何将一个整数限制为3位

[英]How To Limit An Int To 3 Digits

I am wondering if anyone knows how I could limit an integer to 3 digits. 我想知道是否有人知道如何将整数限制为3位数字。 If the number is shorter than 3 digits, I want to output a number prepended with zeroes. 如果该数字短于3位数字,我想输出一个以零开头的数字。 If the number is longer than 3 digits, I want to output only the leading three digits. 如果数字长于3位,我只想输出前三位。

For example: 例如:

  • If a "long" number such as 382198 is inputted, the expected output would be 382 . 如果输入“长”数字(例如382198 ),则预期输出将为382
  • If a "short" number such as 62 is inputted, the expected output would be 062 . 如果输入“短”数字(例如62 ),则预期输出将为062
  • If a number with exactly 3 digits such as 123 is inputted, the expected output would be 123 . 如果输入正好是3位的数字(例如123 ),则预期输出将是123

I have tried using DecimalFormat and StringFormat, but I did not have any success with either. 我尝试使用DecimalFormat和StringFormat,但两者均未成功。 I would like to avoid creating any extra objects if possible. 如果可能,我想避免创建任何其他对象。

Thanks! 谢谢!

You can do something like this: 您可以执行以下操作:

 public class DigitsFormatter {
    public static void main(String[] args) {
        System.out.println(limitDigits(123232)); //123
        System.out.println(limitDigits(12)); //012
    }

    public static String limitDigits(int n) {
        String str = String.valueOf(n);
        if (str.length() > 3) {
            str = str.substring(0,3);
        }
        return String.format("%03d", Integer.valueOf(str));
    }
}

This example code shows how to use '/' and System.out.printf to obtain what you want without expensive Objects being created 此示例代码显示如何使用'/'和System.out.printf获得所需的内容,而无需创建昂贵的对象

    int val = 99;
    while (val > 1000) 
        val = val / 10;

    System.out.printf("%03d%n", val);

    val = 123456;
    while (val > 1000) 
        val = val / 10;

    System.out.printf("%03d%n", val);

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

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