Format NumeralJS percentages without multiplying by 100
Asked Answered
V

3

6

In Handsontable, you can use the format option on a numeric cell to format the values accordingly. Since it uses NumeralJS, I looked through the documentation to see how to format a number to just add the % sign and not multiply by 100 but can't find how to do this without setting my own.

Example cell:

{
    "type": "numeric",
    "format": "0.00%"
}

When the value is 7, it displays "700.00%". I'd like it to show `"7.00%". Any way of doing this in handsontable?

Violist answered 31/12, 2014 at 17:15 Comment(0)
C
2

I do not think there is a way to do this currently without making changes to the numeral.js file.

If you want, you can edit function formatPercentage (found in numberal.js) by removing the * 100 part:

function formatPercentage (n, format, roundingFunction) {
    var space = '',
        output,
        value = n._value/* * 100*/; // comment out or remove * 100 here

    ...
}
Chessman answered 25/2, 2015 at 12:6 Comment(3)
Alright, good to know. I ended up formatting it manually with regex using a custom renderer but this would work too.Violist
Unfortunately I had to resort to modifying numeral.js.Jeaniejeanine
Pushed a PR, but I'm not too optimistic when looking at the number of unmerged PRs.Jeaniejeanine
P
6

For anyone still looking for the easiest way of achieving this, there is a numeral option you can set like so:

numeral.options.scalePercentBy100 = false;

Credit to Csaba Toth for creating the PR. PR Here

Pubis answered 25/8, 2020 at 15:48 Comment(0)
C
2

I do not think there is a way to do this currently without making changes to the numeral.js file.

If you want, you can edit function formatPercentage (found in numberal.js) by removing the * 100 part:

function formatPercentage (n, format, roundingFunction) {
    var space = '',
        output,
        value = n._value/* * 100*/; // comment out or remove * 100 here

    ...
}
Chessman answered 25/2, 2015 at 12:6 Comment(3)
Alright, good to know. I ended up formatting it manually with regex using a custom renderer but this would work too.Violist
Unfortunately I had to resort to modifying numeral.js.Jeaniejeanine
Pushed a PR, but I'm not too optimistic when looking at the number of unmerged PRs.Jeaniejeanine
F
0

Perhaps better than overriding numeral JS logic, you could also just numeral the number to the decimal precision you want and then concatenate the percent symbol at the end.

formatPercent(number) {
    return `${numeral(number).format('0.00')}%`;
}
Finished answered 9/1, 2020 at 13:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.