-1

I have been trying to come up with a way without using someone's plugin to format a number with decimals to currency without decimals. I have found the below to be the easiest way thus far:

yourVar.toLocaleString("en", { style: 'currency', currency: 'USD' }).split('.')[0]

example:

before:446882086.00

after:$446,882,086
khemikal
  • 83
  • 6

1 Answers1

0

With help from this question :Add commas or spaces to group every three digits

I have created this function :

function convertString(currency, input) {
  var thisInt = Math.round(input); //this removes numbers after decimal   
  var thisOutputValue = currency + commafy(thisInt); //add currency symbol and commas

  return thisOutputValue;
}


function commafy(num) {
  var str = num.toString().split('.');
  if (str[0].length >= 5) {
    str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
  }
  if (str[1] && str[1].length >= 5) {
    str[1] = str[1].replace(/(\d{3})/g, '$1 ');
  }
  return str.join('.');
}    

var changeIntToCurrencyString = convertString('$', 435345.00) //change numbers into dollars

console.log(changeIntToCurrencyString )

The above code converts the integer 435345.00 to dollar currency string : $435,345. It should work for all other integer values :)

Fiddle : https://jsfiddle.net/thatOneGuy/zL817x5a/3/

function convertString(currency, input) {
  var thisInt = Math.round(input); //this removes numbers after decimal   
  var thisOutputValue = currency + commafy(thisInt); //add currency symbol and commas

  return thisOutputValue;
}


function commafy(num) {
  var str = num.toString().split('.');
  if (str[0].length >= 5) {
    str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
  }
  if (str[1] && str[1].length >= 5) {
    str[1] = str[1].replace(/(\d{3})/g, '$1 ');
  }
  return str.join('.');
}

var tryoutint = 435345.00;
var changeIntToCurrencyString = convertString('$', tryoutint) //change numbers into dollars

console.log(changeIntToCurrencyString)
alert(tryoutint + ' : ' + changeIntToCurrencyString)
Community
  • 1
  • 1
thatOneGuy
  • 9,977
  • 7
  • 48
  • 90