0

I use NumeralJS for formatting amounts as below;

numeral(unformattedValue).format(amtFormat);

So if the amtFormat is set as "0,0.00", then if the amount is entered as "123.1", I get it as "123.10"

But what I want is no formatting/rounding, etc to take place after the decimal... Thus, if the entered value is 1.999999, I want the output to be 1.999999 (No change after the decimal at all)

Is it possible to pass something to the format() to achieve this ? I could not find anything in the NumeralJS documentation.

copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • I'm not sure I understand, why call `format` if you don't need any formatting? Could you just call `value()`? – JoshG Jun 19 '20 at 04:30
  • Actually, there are 2 things...thousand separator formatting (which I want to be applied), but the decimals should stay as it is... – copenndthagen Jun 19 '20 at 04:36

1 Answers1

0

Given your requirements of:

  • Formatting the thousands separator
  • Keeping the decimals "as-is"

One option you could try is below. There might be a simpler way to do this, perhaps by defining a custom format, but here's one thought:

// example input
let input = [1549.9988, 1549123.9912938, 123.456];

input.forEach(i => {

    // count the number of decimals
    let numberOfDecimals = i.toString().split(".")[1].length;

    // construct a string representing the number of decimals to retain
    let decFormat = "0".repeat(numberOfDecimals - 1);

    // format the number using this string
    let num = numeral(i).format("0,0[." + decFormat + "]");

    console.log(num);
    
});
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
JoshG
  • 6,472
  • 2
  • 38
  • 61
  • Thanks a lot..actually generating random number of 0s to format is something which I have tried already and it works perfectly...What I was looking for is if there is any way of avoiding that and using some built-in way of NumeralJS to achieve the same.... – copenndthagen Jun 19 '20 at 05:05
  • I looked a bit into how `format` works, and short of creating your own custom format where you could apply a regex, it looks like there aren't many (if any) other built-in options. I agree this would be a useful feature though. Might be worth opening up an issue on GitHub with the dev team. – JoshG Jun 19 '20 at 06:06