Reputation: 1689
Here is how my method is currently defined in Scala, i've been following this Stackoverflow answer
def digitFormatter(long: Long, numDigits: Int): String = {
String.format(s"%0${numDigits}d", long)
}
This seems to work ok with postive integers, i get this expected behavior
assert(digitFormatter(0, 1) == "0")
assert(digitFormatter(0, 2) == "00")
assert(digitFormatter(1, 2) == "01")
assert(digitFormatter(10, 2) == "10")
However this doesn't seem to work with negative numbers, this is what I would expect my output to be
assert(
digitFormatter(-1, 2) == "-01")
However the result I get is just -1
. How do I pad leading zeroes on negative numbers using the java std libraries?
Upvotes: 1
Views: 1149
Reputation: 12102
Unfortunately, there is no Java format available that does this: They format on total string width, not on number of zeroes. The easiest way is to vary the length of the padding depending on whether the argument is negative:
def digitFormatter(long: Long, numDigits: Int): String = {
val padlength = if (long >= 0) numDigits else numDigits + 1
String.format(s"%0${padlength}d", long)
}
Upvotes: 1
Reputation: 8529
String.format
should not be used at Scala. You can read the post The Scala String format approach (and Java String.format) by Alvin Alexander.
To make it work in Scala you need to do:
def digitFormatter(long: Long, numDigits: Int): String = {
val padlength = if (long < 0) numDigits + 1 else numDigits
s"%0${padlength}d".format(long)
}
You can find the format method in Scala docs. Code run can be found at Scastie.
Upvotes: 0
Reputation: 103018
You've mischaracterised what String.format does. In your code, you have ${numDigits}
which suggests you think that number in front of the d
is the number of digits.
No, it's the number of characters.
In other words:
String.format("%05d", -12)
produces the string -0012
, because you asked for a string which is at minimum 5 characters long, and which applies 0-padding to get to 5 characters.
If you want a method which turns e.g. -12
into -00012
(6 characters, 5 digits) and +12 into 00012
(5 characters, 5 digits), then you'd have to do something like:
def digitFormatter(long: Long, numDigits: Int): String = {
var numChars = numDigits + (if (long < 0) 1 else 0)
String.format(s"%0${numChars}d", long)
}
NB: I'm not a scala programmer, I'm taking a bit of a stab with that ternary operator, but I think you can do that in scala.
Upvotes: 2
Reputation: 3027
You can do it just as below:
String result = ((value < 0) ? "-" : "") + String.format("%05d", Math.abs(value));
Upvotes: -1