Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: pad start and end of decimal number to make fixed-length string

Tags:

javascript

I'm looking for a neat way of padding a positive or negative decimal number to create a fixed-length string, for example:

32.91    --> +032.9100
-2.1     --> -002.1000
 0.32546 --> +000.3255

It's easy enough to achieve (I've posted my attempt as an answer), but everything I've tried so far seems an awful lot more unwieldy than it ought to be. I'm sure there are some neat one-liners out there...

like image 390
drmrbrewer Avatar asked Nov 22 '25 12:11

drmrbrewer


1 Answers

Here is Nina's solution compared with my own (slightly longer) solution:

const fix1 = function (value, left, right) {
    return (value < 0 ? '-' : '+') + Math.abs(value).toFixed(right).padStart(left + right + 1, '0');
};
const fix2 = function (value, left, right) {
    var padded = Math.round(Math.abs(value) * Math.pow(10, right)).toString().padStart(left + right, '0');
    var withPoint = padded.substr(0, left) + '.' + padded.substr(left);
    var withSign = (value < 0 ? '-' : '+') + withPoint;
    return withSign;
};
console.log(fix1(6.55, 3, 1));  // +006.5
console.log(fix2(6.55, 3, 1));  // +006.6

I have a distrust of toFixed() because it fails in some situations, like the above.

like image 115
drmrbrewer Avatar answered Nov 25 '25 02:11

drmrbrewer