bn.js icon indicating copy to clipboard operation
bn.js copied to clipboard

Wrong padding in toString() function

Open macor161 opened this issue 7 years ago • 7 comments
trafficstars

When the length of a number is larger than the requested padding, toString will add an unnecessary padding.

For example:

new BN('123').toString(10, 2)

Should return 123 but returns 0123.

Or

new BN('12345678').toString(10, 6)

Should return 12345678 but returns 000012345678.

A simple fix would be to first check if the length is actually smaller than the requested padding before applying it.

I can submit a pull request to fix this issue.

macor161 avatar Sep 12 '18 00:09 macor161

I can submit a pull request to fix this issue.

@macor161 please do!

But if you don't have time, please please submit a failing test :+1:

dcousens avatar Sep 12 '18 01:09 dcousens

wow, currently this looks like not padding at all? :thinking: https://github.com/indutny/bn.js/blob/e69c617b3297b99aca429f30842e27979ef9beb5/lib/bn.js#L474

fanatid avatar Sep 12 '18 07:09 fanatid

I submited a pull request with the fix and a test. Let me know if you need anything else!

macor161 avatar Sep 14 '18 12:09 macor161

@macor161 I think you're right to bring the https://github.com/indutny/bn.js/pull/199 conversation back here until we reach some kind of consensus

@fanatid @dcousens

therightstuff avatar Sep 17 '18 09:09 therightstuff

@therightstuff I like the idea of changing the signature, I think it's better than introducing a new function.

What do you think of those 2 signatures?:


toString(base: number, bytePadding: number);
toString(options: Object);

Internally, it would look something like this:


toString(base: number | options: Object, [bytePadding: number])

And options would be:

base: number = 10
bytePadding: number = 0
padding: number = 0

This keeps the function backward compatible and is easily extendible

macor161 avatar Sep 17 '18 11:09 macor161

Let me know when you reach a consensus, I will submit a pull request! :)

macor161 avatar Sep 19 '18 01:09 macor161

I will close this issue as there doesn't seem to be any activity.

macor161 avatar Nov 22 '18 14:11 macor161