Format number with thousandseparator?
Hi, I'm going to print out a lot of big numbers on a custom screen in CS, and would like to include a thousandseparator to make the formatting prettier.
For example, instead of printing "100000000" I'd like it to be "100 000 000".
Does anyone have a codesnippet for doing this?
Alles Antwoorden (3)
String test = "1234567";
Integer len = test.getLength() - 3;
while (len > 0)
{
test = test.subString(0, len) + " " + test.subString(len, test.getLength() - len);
len -= 3;
}
print(test);
Thanks!
I ended up with this one, but yours is shorter (= better).
String FormatStringAsThousandSeparated(String number)
{
Byte[] bytes = number.toByteArray();
Byte[] newBytes;
Integer index = 0;
for (Integer i = bytes.length()-1; i >= 0; i--)
{
if (index % 3 == 0 && index > 0)
newBytes.pushFront(Byte(32)); //32 = whitespace. 46 = Period
index++;
newBytes.pushFront(bytes[i]);
}
return String(newBytes).stripLeading(" ");
}
Hi,
I don't know if this is of any use to anyone, but I have created two functions for this base on Sverre's code above, one for an Integer number, and one for a Float.
#setLanguageLevel 4;
String FormatIntegerWithThousandSeparator(Integer inputNumber, String thousandSeperator)
{
//Convert The Number Into A String
String strInputNumber = inputNumber.toString();
//Loop Back In Blocks Of Three, And Add Thousand Seperators
Integer len = strInputNumber.getLength() - 3;
while (len > 0)
{
strInputNumber = strInputNumber.subString(0, len) + thousandSeperator + strInputNumber.subString(len, strInputNumber.getLength() - len);
len -= 3;
}
//Return Formatted Number
Return strInputNumber;
}
String FormatFloatWithThousandSeparator(Float inputNumber, String thousandSeperator, Integer noOfDecimalPlaces)
{
//Split The Number Into A Whole Number And It's Decimals
Integer inputNumberWholeNumber = inputNumber.floor();
Float remainingValue = inputNumber - inputNumberWholeNumber;
String strRemainingValue = remainingValue.toString(noOfDecimalPlaces);
//Format The Whole Number Into The Thousand Seperators And Add Back The Decimals
Return FormatIntegerWithThousandSeparator(inputNumberWholeNumber, thousandSeperator) + strRemainingValue.subString(1, strRemainingValue.getLength());
}
//Test Functions
print(FormatIntegerWithThousandSeparator(123456789, ",") + '
');
print(FormatFloatWithThousandSeparator(123456789.99, ",", 2) + '
');
print(FormatIntegerWithThousandSeparator(325233585, ",") + '
');
print(FormatFloatWithThousandSeparator(325233585.22, ",", 2) + '
');
print(FormatFloatWithThousandSeparator(325233585.00, ",", 2) + '
');
Trevor