Use Sprintf() to Add Trailing Zeros

Use sprintf() to add trailing zeros

As noted in the comments, sprintf() won't do this. But the stringi package has padding functions that are quick and easy.

id <- c(2331, 29623, 311, 29623)

library(stringi)
stri_pad_left(id, 5, 0)
# [1] "02331" "29623" "00311" "29623"
stri_pad_right(id, 5, 0)
# [1] "23310" "29623" "31100" "29623"

These functions dispatch directly to C code, so they should be sufficiently efficient.

How to have sprintf to ignore trailing zeros

Simply use g instead of f:

sprintf('%.15g', 3.0001)

ans =

3.0001

From doc sprintf

  • %g The more compact form of %e or %f with no trailing zeros

The above method fails for numbers lower than 0.0001 (1e-4), in which case an alternative solution is to use %f and then regexprep here it replaces one more more zeros followed by a space with a space:

str = sprintf('%.15f ',mat);
str = regexprep(str,'[0]+ ',' ')

This method also has an issue with numbers lower than 5e-16 (such that there are only zeros for 15 digits to the right of the decimal point) having these significant digits removed.

To solve this instead of blindly replacing zeros, we can replace a digit in the range 1-9 followed by one or more zeros and then a space with that digit followed by a space:

str = sprintf('%.15f ',mat);
str=regexprep(str,'([1-9])[0]+ ','$1 ')

Trailing Zeros in printf/sprintf

printf and its variants can pad zeroes to the left, not to the right. sprintf the number, then add the necessary zeros yourself, or make sure the number is 6 digits long:

while(num < 100000) 
num *= 10;

(This code assumes the number isn't negative, or you're going to get in trouble)

Use sprintf to round a matrix while keeping trailing zeros in R

You can use the dim attribute of your original matrix to specify the dim attribute of your output matrix:

tbl[] <- `dim<-`(sprintf("%.1f", tbl), dim(tbl))
tbl
# a b
# c "2.4" "1.0"
# d "4.0" "2.3"

Note: There's no point in rounding your matrix before passing it to sprintf.

Display trailing zeros with signif

Just format the values using sprintf before printing them:

sprintf('%#.2g', c(0.301, 0.000502))
[1] "0.30" "0.00050"

How to add user defined variable leading zeros in C sprintf?

To make the width dynamic (not hard-coded in the format string), you write it like this:

sprintf(CNum,"%0*ld",blank,num); 

Instead of a hard-coded width 3 as in "%03ld", the asterisk indicates that the next argument (which must be of type int) is to be taken as the width.

Add trailing zeros to string

If you don't know how long your original input will be and you want the padding to be flexible (I assume that is what you need...), you can set the padding to the other side like this:

$number= sprintf("%-04s", "02");
^ here
echo $number;

Ruby: How to add zeros to front of a number string using sprintf()

Your usage of sprintf is fine. Your problem is that 062 (and 0016) is octal (as is any integer that starts with a 0), and it becomes 50 when converted to base10.

The solution is to get rid of that 0 before it hits your Ruby app. Presuming that it's a string (because your examples show strings), you can do something like this:

"062".gsub /^0/, ''

And then carry on with the padding and print formatting.

The other way is to knowingly print it as an octal if you know it starts with a 0:

"%05o" % 062 # => "00062"

Of course, if you have control over the input, your best bet is to ensure people can't break your code by inputting numbers you don't expect. eg.

"%05s" % 0xff0055 # => 16711765
"%05x" % 0xff0055 # => "ff0055"

Checking inputs changes the problem from being a formatting one to a validation one, and it's better to prevent than treat.

(the quirky % syntax is sugar for printf/sprintf)

PHP: How to add leading zeros/zero padding to float via sprintf()?

Short answer: sprintf('%05.2f', 1); will give the desired result 01.00

Note how %02 was replaced by %05.

Explanation

This forum post pointed me in the right direction: The first number does neither denote the number of leading zeros nor the number of total charaters to the left of the decimal seperator but the total number of characters in the resulting string!

Example

sprintf('%02.2f', 1); yields at least the decimal seperator "." plus at least 2 characters for the precision. Since that is already 3 characters in total, the %02 in the beginning has no effect. To get the desired "2 leading zeros" one needs to add the 3 characters for precision and decimal seperator, making it sprintf('%05.2f', 1);

Some code

$num = 42.0815;

function printFloatWithLeadingZeros($num, $precision = 2, $leadingZeros = 0){
$decimalSeperator = ".";
$adjustedLeadingZeros = $leadingZeros + mb_strlen($decimalSeperator) + $precision;
$pattern = "%0{$adjustedLeadingZeros}{$decimalSeperator}{$precision}f";
return sprintf($pattern,$num);
}

for($i = 0; $i <= 6; $i++){
echo "$i max. leading zeros on $num = ".printFloatWithLeadingZeros($num,2,$i)."\n";
}

Output

0 max. leading zeros on 42.0815 = 42.08
1 max. leading zeros on 42.0815 = 42.08
2 max. leading zeros on 42.0815 = 42.08
3 max. leading zeros on 42.0815 = 042.08
4 max. leading zeros on 42.0815 = 0042.08
5 max. leading zeros on 42.0815 = 00042.08
6 max. leading zeros on 42.0815 = 000042.08


Related Topics



Leave a reply



Submit