-1

I want to separate the numbers with a comma as follows. How can it be done?

number              display
----------        ------------
1.00                   1
1.20                   1.20
1234                   1,234
1234.89                1,234.89

i use from:

@Html.TextBox("", FormattedValue, new { @class = "form-control text-center
number", lang = "en" })

<script>
  $('.number').priceFormat({
    prefix: '',
    thousandsSeparator: ',',
    insertPlusSign: '',
    centsLimit: 2,
  });
</script>

but This code always displays numbers with two decimal places, even if the decimal point is zero

Lashan Fernando
  • 1,187
  • 1
  • 7
  • 21
Miss
  • 171
  • 1
  • 4
  • 10
  • 1
    What is `priceFormat`? Can you check their documentation? – evolutionxbox Dec 26 '20 at 13:36
  • So the title of your question focusses on the wrong thing, since you have the thousands separator working. But the problem is the decimals at the end? Better focus on that then... – trincot Dec 26 '20 at 13:36
  • https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – Ken Lee Dec 26 '20 at 13:38

2 Answers2

1

Your only issue with the approach you already have is that 1.00 should be rendered as just 1, with no decimal component. If so, you could just use a regex replacement.

var number = $('.number').priceFormat({
        prefix: '',
        thousandsSeparator: ',',
        insertPlusSign: '',
        centsLimit: 2
    });

number = number.replace(/\.00$/, "");
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Easy to do, using the toLocaleString method from the standard library:

number.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 2})

btw using this method without any arguments would format the number based on the user local setting, which is cool if you have users from multiple regions.

Jencel
  • 722
  • 7
  • 17