format number javascript code example

Example 1: how to number format in javascript

function formatNumber(num) {
  return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}

console.info(formatNumber(2665)) // 2,665
console.info(formatNumber(102665)) // 102,665
console.info(formatNumber(111102665)) // 111,102,665
console.info(formatNumber(1240.5)) // 1,240.5
console.info(formatNumber(1000240.5)) // 1,000,240.5

Example 2: js format urcurency

// Create our number formatter.
var formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});

formatter.format(2500); /* $2,500.00 */

Example 3: javascript format price

// Javascript has a number formatter (part of the Internationalization API).

const number = 123456.789;

// another example 
console.log(new Intl.NumberFormat('ja-JP',  {
  style: 'currency',
  currency: 'BWP',
}).format(number));

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

Example 4: float to currency js

function floatToEuro(float){
    var euroCurrency 
    euroCurrency = '\u20AC' + float.toLocaleString('nl-NL',{minimumFractionDigits: 2});
    console.log(euroCurrency);
    return euroCurrency;
};

Example 5: javascript convert a number in string

const num = 123; //> type number 123
const str = num.toString(); //> type string "123"

Example 6: get the whole value of a number javascript

var value = 2.9802453587962963;
var wholeNum = Math.floor(value);
console.log(wholeNum);  // output ==> 2