简体   繁体   English

减去时保持前导零

[英]Keep leading Zeros when subtracting

I would like to know how to keep leading 0s when subtracting numbers, specifically two longs. 我想知道在减去数字(特别是两个long)时如何保持前导0。

Lets say 1000 - 0999 = 0001 假设1000-0999 = 0001

I want to keep the answer as a long as well. 我也想保留很长的答案。 So just adding the 0s in the front isnt going to work. 因此,仅在前面添加0不会起作用。

Any thoughts? 有什么想法吗?

This is a printing problem: 这是打印问题:

long n = 1000 - 999;
String s = String.format("%04d", n);  // 0001

More info: Formatter 更多信息: Formatter

Leading zeroes are just punctuation. 前导零只是标点符号。 The whole concept applies only to a string that is supposed to represent the number. 整个概念仅适用于应该表示数字的字符串。 In fact, until you produce such a string, even the concept of "digit" is meaningless. 实际上,在生成这样的字符串之前,即使“数字”的概念也毫无意义。

So your real question isn't "How do I keep leading zeroes when subtracting?", but rather "How do I get leading zeroes when formatting my result as a string?" 因此,您真正的问题不是“减时如何保持前导零?”,而是“将结果格式化为字符串时如何获得前导零?”

So, for example, to print a number using (at least) 4 digits, with leading zeroes, you might use out.printf("%04d", theNumber) . 因此,例如,要使用(至少)4位数字(带前导零)来打印数字,可以使用out.printf("%04d", theNumber) Or use the same format specifier when creating a string. 或在创建字符串时使用相同的格式说明符。

As @Sotirios Delimanolis mentioned, you can't do this with longs. 正如@Sotirios Delimanolis所提到的,您不能长期这样做。 You will need to use a string, because longs can't store extra zeros in the front. 您将需要使用字符串,因为long不能在前面存储额外的零。 Try this: 尝试这个:

public String subtractWithZeros(long number1, long number2){
    long result = number1 - number2;
    String strResult = String.valueOf(result);
    String strNum1 = String.valueOf(number1);
    String strNum2 = String.valueOf(number2);
    int totalLength = Math.max(strNum1.length(), strNum2.length());
    int numOfNeededZeros = totalLength - strResult.length();
    for(int i = 0;i<numOfNeededZeros;i++){
        strResult = "0" + strResult;
    }
    return strResult;
}

This should return a long with the zeros you wanted at the front. 这应该返回一个很长的字符,并在前面加上您想要的零。 I am assuming the result of subtraction will never be negative. 我假设减法的结果永远不会是负数。

While this is not the contemporary answer for this [common] question, it is a way to manipulate the "printf" and "format" parameters. 尽管这不是此[常见]问题的当代答案,但它是一种操纵“ printf”和“ format”参数的方法。

int number = 5_000;

int length = Integer.toString(number).length();

number -= 4_999;

System.out.printf("%0" + length + "d", number);

// result :  0001

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

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