JavaScript; How to set dot after three digits?
Asked Answered
P

6

5

I have the following JavaScript code:

var calculation = $('select[name=somevalue1] option:selected').data('calc')-($('select[name=somevalue1] option:selected').data('calc')/100*$('select[name=somevalue2] option:selected').data('calc'))-($('select[name=somevalue1] option:selected').data('calc')-($('select[name=somevalue1] option:selected').data('calc')/100*$('select[name=somevalue2] option:selected').data('calc')))/100*$('select[name=somevalue3] option:selected').data('calc');
    
$('#calculation').text((calculation).toFixed(2).replace(".",","))

That will calculate a number, change . to , and round it to two digits after comma.

What I need to do is to add a dot after tree digits before come.

Means:

1.234,56 instead of 1234,56

1.234.567,89 instead of 1234567,89

Does anybody know a way to do that?

Preordain answered 24/3, 2017 at 5:53 Comment(3)
numeraljs.comBrogan
@Brogan 1. I don't really understand how it works. 2. I don't want to use a library.Preordain
add the corresponding HTML code. Then we can give a trySmalley
P
11

This code worked for me:

<p id="calculation"></p>

<script>
    function numberWithCommas(x) {
        var parts = x.toString().split(".");
        parts[0]=parts[0].replace(/\B(?=(\d{3})+(?!\d))/g,".");
        return parts.join(",");
        }

        var calculation = 1231739216.34367;

        document.getElementById("calculation").innerHTML = numberWithCommas((calculation).toFixed(2))
</script>

This code will:

  1. Round (for business) to two digits after dezimal.
  2. Change the decimal dot to comma.
  3. Set a dot every third digit before decimal.
Preordain answered 24/3, 2017 at 6:33 Comment(0)
A
7

ECMAScript Internationalization API has a number formatting funciton. Intl.NumberFormat()

You can use it like this with pure javascript:

var calculation = document.getElementById('money').value;

//1st way
var moneyFormatter  = new Intl.NumberFormat();
document.getElementById('formattedMoney').innerText = moneyFormatter.format(calculation);

// 2nd way, using currency
var moneyFormatter2 = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2
});

document.getElementById('formattedMoney2').innerText = moneyFormatter2.format(calculation);
<label>Calculation:</label> <input type="text" value="123456789.25" name="money" id="money" />

<ul>
  <li>Number Format: <b><span id="formattedMoney"></span></b><br/><br/></li>
  <li>Currency Format: <b><span id="formattedMoney2"></span><b/></li>
</ul>

IE11, Firefox and Chrome support it, but i am not sure about other browsers.

http://www.ecma-international.org/ecma-402/1.0/#sec-11.1.2

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

Ascending answered 24/3, 2017 at 6:49 Comment(0)
P
2

You should use an additional String#replace with a regular expression (to match digits in groups of threes before the ,) and a replacement function (to prepend . to each match).

Your Updated Code:

var calculation = $('select[name=somevalue1] option:selected').data('calc') - ($('select[name=somevalue1] option:selected').data('calc') / 100 * $('select[name=somevalue2] option:selected').data('calc')) - ($('select[name=somevalue1] option:selected').data('calc') - ($('select[name=somevalue1] option:selected').data('calc') / 100 * $('select[name=somevalue2] option:selected').data('calc'))) / 100 * $('select[name=somevalue3] option:selected').data('calc')

function format(n) {
  return n.toFixed(2).replace('.', ',').replace(/\d{3}(?=(\d{3})*,)/g, function(s) {
    return '.' + s
  })
}

$('#calculation').text(format(calculation))


Demo Implementation:

var calculations = [
  1234.56,
  1234567.89,
  1234,
  .12
]

function format (n) {
  return n.toFixed(2).replace('.', ',').replace(/\d{3}(?=(\d{3})*,)/g, function (s) {
    return '.' + s
  })
}

console.log(calculations.map(format))
Photomicrograph answered 24/3, 2017 at 6:17 Comment(0)
K
2

On modern browsers (Chrome 24+, Firefox 29+, IE11) you can use Number.prototype.toLocaleString()

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

var number = 3500.12;
console.log(number.toLocaleString());

This uses the locale of the browser to format the number automatically. My browser is set to German so the output is

3.500,12

If someone with a different locale uses your site they will see the numbers as they expect them.

Knave answered 24/3, 2017 at 7:15 Comment(0)
C
1

This function will work for you:

function formatNumber(num) {
  var first = num.split(',');
  var digits = first[0].split('').reverse();
  var new_digits = [];
  for(var i =0; i<digits.length; i++) {
    if((i+1)%3==0) {
      new_digits.push(digits[i]);
      new_digits.push('.');
    }
    else {
      new_digits.push(digits[i]);
    }
  }
  var new_num = new_digits.reverse().join("")+','+first[1];
  return new_num;
}
Cd answered 24/3, 2017 at 6:23 Comment(0)
P
0

I came here from google only for the 3-digit formatting part, so here's vanilla code for just that:

Format to 3 Digits - Basic Function
function formatThreeDigits( integerStr ){
  var len = integerStr.length;
  var formatted = "";
  
  var breakpoint = (len-1) % 3; // after which index to place the dot
  
  for(i = 0; i < len; i++){
    formatted += integerStr.charAt(i);
    if(i % 3 === breakpoint){
      if(i < len-1) // don't add dot for last digit
        formatted += ".";
    }
  }

  return formatted;
}
console.log( formatThreeDigits("123456789") ); // "123.456.789"
Format to 3 Digits - Advanced Function

function formatThreeDigits(num, decimalDelimiter, digitSeparator){
  // default secondary arguments
  if(arguments.length < 3) digitSeparator = "."; // 3.000.000
  if(arguments.length < 2) decimalDelimiter = ","; // 3,14
  
  let numParts = []; // [0] => integer, [1] => possible decimal part
  let negative = false; // negative or not (e.g. -1)
  
  if( num.substring ){
    // if passed "num" is a STRING:
    numParts = num.split( decimalDelimiter );
  } else {
    // if passed "num" is a NUMBER
    if( num < 0 ){
      negative = true;
      num = num * -1; // turn positive
    }
    
    const numString = num.toString();
    
    // check if it's a decimal number (e.g. 3.14), as it would already have a '.' in it then
    numParts = numString.split(".");
  }
  
  let integer = numParts[0];
  
  const len = integer.length;
  if( len <= 3 ) return (negative ? "-" + num : num); // remember minus if negative!
  
  const breakpoint = ( len - 1 ) % 3; // after which index to place the dot
  
  let formattedNumString = "";
  formattedNumString = negative ? "-" : ""; // prefix "-" is negative
  const loopEnd = len - 3;
  
  for(var i = 0; i < loopEnd; i++){
    formattedNumString += integer.charAt(i);
    if(i % 3 === breakpoint){
      formattedNumString += digitSeparator;
    }
  }
  formattedNumString += integer.substr(-3, 3);
  formattedNumString += numParts[1] ? decimalDelimiter + numParts[1] : "";
  
  return formattedNumString;
}

Here's the same code, but with all the bells and whistles, options, edge cases covered, slightly optimised, and decimal numbers taken into account.

Petticoat answered 31/12, 2023 at 22:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.