Yoel
Yoel

Reputation: 7985

custom format in numeral.js negative number (-20) to be 20(-)

I use the numeral.js library

I am interested in Do custom format That wherever there is a negative number (like - 20) the library will show it to me so 20 (-)

I need the minus sign to be in parentheses

How can I do this?

Upvotes: 1

Views: 638

Answers (1)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

You could do something similar to this

numeral.register('format', 'negative', {
    regexps: {
        format: /(-)/,
        unformat: /(-)/
    },
    format: function(value, format, roundingFunction) {
        return value < 0 ? -value + " (-)" : value;
    },
    unformat: function(s) {
        return s.endsWith(" (-)") ? -parseInt(s.substr(0, s.length - 4)) : parseInt(s);
    }
});

// use your custom format
const result = numeral(-5).format('(-)');
const unresult = numeral(result).format();
console.log(result)
console.log(unresult)
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>

Upvotes: 1

Related Questions