JavaScript - easy way to format something to currency w/out decimals - javascript

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

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)

Related

NaN (not a number) when attempting output 2 decimal place for money value [duplicate]

I have a text box that will have a currency string in it that I then need to convert that string to a double to perform some operations on it.
"$1,100.00" → 1100.00
This needs to occur all client side. I have no choice but to leave the currency string as a currency string as input but need to cast/convert it to a double to allow some mathematical operations.
Remove all non dot / digits:
var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9.-]+/g,""));
accounting.js is the way to go. I used it at a project and had very good experience using it.
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
accounting.unformat("€ 1.000.000,00", ","); // 1000000
You can find it at GitHub
Use a regex to remove the formating (dollar and comma), and use parseFloat to convert the string to a floating point number.`
var currency = "$1,100.00";
currency.replace(/[$,]+/g,"");
var result = parseFloat(currency) + .05;
I know this is an old question but wanted to give an additional option.
The jQuery Globalize gives the ability to parse a culture specific format to a float.
https://github.com/jquery/globalize
Given a string "$13,042.00", and Globalize set to en-US:
Globalize.culture("en-US");
You can parse the float value out like so:
var result = Globalize.parseFloat(Globalize.format("$13,042.00", "c"));
This will give you:
13042.00
And allows you to work with other cultures.
I know this is an old question, but CMS's answer seems to have one tiny little flaw: it only works if currency format uses "." as decimal separator.
For example, if you need to work with russian rubles, the string will look like this:
"1 000,00 rub."
My solution is far less elegant than CMS's, but it should do the trick.
var currency = "1 000,00 rub."; //it works for US-style currency strings as well
var cur_re = /\D*(\d+|\d.*?\d)(?:\D+(\d{2}))?\D*$/;
var parts = cur_re.exec(currency);
var number = parseFloat(parts[1].replace(/\D/,'')+'.'+(parts[2]?parts[2]:'00'));
console.log(number.toFixed(2));
Assumptions:
currency value uses decimal notation
there are no digits in the string that are not a part of the currency value
currency value contains either 0 or 2 digits in its fractional part *
The regexp can even handle something like "1,999 dollars and 99 cents", though it isn't an intended feature and it should not be relied upon.
Hope this will help someone.
This example run ok
var currency = "$1,123,456.00";
var number = Number(currency.replace(/[^0-9\.]+/g,""));
console.log(number);
For anyone looking for a solution in 2021 you can use Currency.js.
After much research this was the most reliable method I found for production, I didn't have any issues so far. In addition it's very active on Github.
currency(123); // 123.00
currency(1.23); // 1.23
currency("1.23") // 1.23
currency("$12.30") // 12.30
var value = currency("123.45");
currency(value); // 123.45
typescript
import currency from "currency.js";
currency("$12.30").value; // 12.30
This is my function. Works with all currencies..
function toFloat(num) {
dotPos = num.indexOf('.');
commaPos = num.indexOf(',');
if (dotPos < 0)
dotPos = 0;
if (commaPos < 0)
commaPos = 0;
if ((dotPos > commaPos) && dotPos)
sep = dotPos;
else {
if ((commaPos > dotPos) && commaPos)
sep = commaPos;
else
sep = false;
}
if (sep == false)
return parseFloat(num.replace(/[^\d]/g, ""));
return parseFloat(
num.substr(0, sep).replace(/[^\d]/g, "") + '.' +
num.substr(sep+1, num.length).replace(/[^0-9]/, "")
);
}
Usage : toFloat("$1,100.00") or toFloat("1,100.00$")
// "10.000.500,61 TL" price_to_number => 10000500.61
// "10000500.62" number_to_price => 10.000.500,62
JS FIDDLE: https://jsfiddle.net/Limitlessisa/oxhgd32c/
var price="10.000.500,61 TL";
document.getElementById("demo1").innerHTML = price_to_number(price);
var numberPrice="10000500.62";
document.getElementById("demo2").innerHTML = number_to_price(numberPrice);
function price_to_number(v){
if(!v){return 0;}
v=v.split('.').join('');
v=v.split(',').join('.');
return Number(v.replace(/[^0-9.]/g, ""));
}
function number_to_price(v){
if(v==0){return '0,00';}
v=parseFloat(v);
v=v.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
v=v.split('.').join('*').split(',').join('.').split('*').join(',');
return v;
}
You can try this
var str = "$1,112.12";
str = str.replace(",", "");
str = str.replace("$", "");
console.log(parseFloat(str));
let thousands_seps = '.';
let decimal_sep = ',';
let sanitizeValue = "R$ 2.530,55".replace(thousands_seps,'')
.replace(decimal_sep,'.')
.replace(/[^0-9.-]+/, '');
// Converting to float
// Result 2530.55
let stringToFloat = parseFloat(sanitizeValue);
// Formatting for currency: "R$ 2.530,55"
// BRL in this case
let floatTocurrency = Number(stringToFloat).toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'});
// Output
console.log(stringToFloat, floatTocurrency);
I know you've found a solution to your question, I just wanted to recommend that maybe you look at the following more extensive jQuery plugin for International Number Formats:
International Number Formatter
How about simply
Number(currency.replace(/[^0-9-]+/g,""))/100;
Works with all currencies and locales. replaces all non-numeric chars (you can have €50.000,00 or $50,000.00) input must have 2 decimal places
jQuery.preferCulture("en-IN");
var price = jQuery.format(39.00, "c");
output is: Rs. 39.00
use jquery.glob.js,
jQuery.glob.all.js
Here's a simple function -
function getNumberFromCurrency(currency) {
return Number(currency.replace(/[$,]/g,''))
}
console.log(getNumberFromCurrency('$1,000,000.99')) // 1000000.99
For currencies that use the ',' separator mentioned by Quethzel Diaz
Currency is in Brazilian.
var currency_br = "R$ 1.343,45";
currency_br = currency_br.replace('.', "").replace(',', '.');
var number_formated = Number(currency_br.replace(/[^0-9.-]+/g,""));
var parseCurrency = function (e) {
if (typeof (e) === 'number') return e;
if (typeof (e) === 'string') {
var str = e.trim();
var value = Number(e.replace(/[^0-9.-]+/g, ""));
return str.startsWith('(') && str.endsWith(')') ? -value: value;
}
return e;
}
This worked for me and covers most edge cases :)
function toFloat(num) {
const cleanStr = String(num).replace(/[^0-9.,]/g, '');
let dotPos = cleanStr.indexOf('.');
let commaPos = cleanStr.indexOf(',');
if (dotPos < 0) dotPos = 0;
if (commaPos < 0) commaPos = 0;
const dotSplit = cleanStr.split('.');
const commaSplit = cleanStr.split(',');
const isDecimalDot = dotPos
&& (
(commaPos && dotPos > commaPos)
|| (!commaPos && dotSplit[dotSplit.length - 1].length === 2)
);
const isDecimalComma = commaPos
&& (
(dotPos && dotPos < commaPos)
|| (!dotPos && commaSplit[commaSplit.length - 1].length === 2)
);
let integerPart = cleanStr;
let decimalPart = '0';
if (isDecimalComma) {
integerPart = commaSplit[0];
decimalPart = commaSplit[1];
}
if (isDecimalDot) {
integerPart = dotSplit[0];
decimalPart = dotSplit[1];
}
return parseFloat(
`${integerPart.replace(/[^0-9]/g, '')}.${decimalPart.replace(/[^0-9]/g, '')}`,
);
}
toFloat('USD 1,500.00'); // 1500
toFloat('USD 1,500'); // 1500
toFloat('USD 500.00'); // 500
toFloat('USD 500'); // 500
toFloat('EUR 1.500,00'); // 1500
toFloat('EUR 1.500'); // 1500
toFloat('EUR 500,00'); // 500
toFloat('EUR 500'); // 500
Such a headache and so less consideration to other cultures for nothing...
here it is folks:
let floatPrice = parseFloat(price.replace(/(,|\.)([0-9]{3})/g,'$2').replace(/(,|\.)/,'.'));
as simple as that.
$ 150.00
Fr. 150.00
€ 689.00
I have tested for above three currency symbols .You can do it for others also.
var price = Fr. 150.00;
var priceFloat = price.replace(/[^\d\.]/g, '');
Above regular expression will remove everything that is not a digit or a period.So You can get the string without currency symbol but in case of " Fr. 150.00 " if you console for output then you will get price as
console.log('priceFloat : '+priceFloat);
output will be like priceFloat : .150.00
which is wrong so you check the index of "." then split that and get the proper result.
if (priceFloat.indexOf('.') == 0) {
priceFloat = parseFloat(priceFloat.split('.')[1]);
}else{
priceFloat = parseFloat(priceFloat);
}
function NumberConvertToDecimal (number) {
if (number == 0) {
return '0.00';
}
number = parseFloat(number);
number = number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1");
number = number.split('.').join('*').split('*').join('.');
return number;
}
This function should work whichever the locale and currency settings :
function getNumPrice(price, decimalpoint) {
var p = price.split(decimalpoint);
for (var i=0;i<p.length;i++) p[i] = p[i].replace(/\D/g,'');
return p.join('.');
}
This assumes you know the decimal point character (in my case the locale is set from PHP, so I get it with <?php echo cms_function_to_get_decimal_point(); ?>).
You should be able to handle this using vanilla JS. The Internationalization API is part of JS core: ECMAScript Internationalization API
https://www.w3.org/International/wiki/JavaScriptInternationalization
This answer worked for me: How to format numbers as currency strings

How to format number to have n whole and decimal digits?

Say I have a float x that has a whole part a and decimal part b i.e. x = a.b. How can I format x in JavaScript such that it'll have at most n digits, as shown below:
const n = 5
format(123.0) == '123'
format(123.01) == '123.01'
format(123.012) == '123.01'
format(0.0123) == '0.0123'
format(0.01234) == '0.0123'
Based on a recently deleted answer that had the logic but didn't really work, I came up with this solution:
const format = (number, digits = 5) => {
const str = number + ''; // convert to string
let [integer, decimal] = str.split('.'); // split by dot delimiter
const integerDigits = integer.length;
if (integerDigits >= digits) {
return integer;
} else {
let decimalDigits = digits - integerDigits;
decimal = Number('0.' + decimal.substring(0, decimalDigits)).toString();
return integer + '.' + decimal.split('.')[1];
}
}

convert formatted currency amount to a double value using regex

I have different currency format that I want to convert into a double value. Example:
1,000,000.00 => 1000000.00
2'345',00 => 2345.00
2'344'334.03 => 1000000.03
I have the following solution which works and is very inefficient.I am trying to figure out some regex way of doing it.
decimalPlace = amount[amount.length - 3];
if (decimalPlace === '.' && amount.indexOf(',') < -1 && amount.indexOf("'") < -1) {
return amount
}
if (decimalPlace === ',' && amount.indexOf("'") < -1) {
value = amount.split('.').join('')
.replace(',', '.')
return value
}
if (decimalPlace === '.' && amount.indexOf(',') > -1) {
value = amount.split(',').join('')
return value
}
if (decimalPlace === ',' && amount.indexOf("'") > -1) {
value = amount.split("'").join('')
.replace(',', '.')
return value
}
if (decimalPlace === '.' && amount.indexOf("'") > -1) {
value = amount.split("'").join('')
return value
}
return amount
I would appreciate any suggestion with this issue.
You've probably made this more complicated then it has to be.
If those are the only formats that need to be supported, you could use a function like this:
var v1 = "1,000,000.00";
var v2 = "2'345',00";
var v3 = "2'344'334.03";
var v4 = "2,00"
function format(str){
if(str.replace(/[^,]/g, "").length === 1){ // Contains only one comma.
str = str.replace(",", ".");
}
if(str.indexOf("'")!=-1){
str = str.replace(/'/g, "").replace(",", ".");
}
return parseFloat(str.replace(/,/g, "")).toFixed(2);
}
[v1, v2, v3, v4].forEach(v => console.log(format(v)));
EDIT: I've added support for values with only one comma.
EDIT 2: Actually, it seems that I've made that mistake myself (making thing complicated).
I think all this can be as simple as:
var v1 = "1,000,000.00";
var v2 = "2'345',00";
var v3 = "2'344'334.03";
var v4 = "2,00"
function format(str){
if(str.replace(/[^,]/g, "").length === 1){ // Contains only one comma.
str = str.replace(",", ".");
}
return parseFloat(str.replace(/[^0-9\.]/g, "")).toFixed(2);
}
[v1, v2, v3, v4].forEach(v => console.log(format(v)));
I'd recommend against relying too much on regular expressions here. The way I'd approach this is in 2 parts.
First, work out what the decimal point is. This will change based on locale but it's very easy to work it out - just create a function which will add a localised decimal point and then return it.
function getDecimalPoint(locale) {
return (1.2).toLocaleString(locale).replace(/\d+/g, "");
}
The benefit of this function is that if you pass in no locale, the current one will be used (which is "en-GB" for me).
Now that you can identify a decimal point, you can use that to split the formatted number into 2 parts - evenything before the decimal (whole numbers) and everything after it (decimals).
function unformatNumber(number, locale) {
// Split the number based on the decimal point.
var numberParts = String(number).split(getDecimalPoint(locale));
// Remove everything that isn't a number from the whole numbers and parse
// it as a number.
var unformatted = Number(numberParts[0].replace(/\D+/g, ""));
// Check to see if there are any decimals. If there are, convert them into
// a decimal and add them to the unformatted result.
var decimals = numberParts[1];
if (decimals && decimals.length) {
unformatted += decimals / Math.pow(10, decimals.length);
}
return unformatted;
}
To use it, simply pass your numbers to the function.
unformatNumber("1,000,000.00"); // -> 1000000
unformatNumber("2'345',00", "fr"); // -> 2345
unformatNumber("2'344'334.03"); // -> 2344344.03
// I know those numbers aren't formatted in French, but you can change your
// format as necessary.
function getDecimalPoint(locale) {
return (1.2).toLocaleString(locale).replace(/\d+/g, "");
}
function unformatNumber(number, locale) {
var numberParts = String(number).split(getDecimalPoint(locale));
var unformatted = Number(numberParts[0].replace(/\D+/g, ""));
var decimals = numberParts[1];
if (decimals && decimals.length) {
unformatted += decimals / Math.pow(10, decimals.length);
}
return unformatted;
}
console.log(unformatNumber("1,000,000.00"));
console.log(unformatNumber("2'345',00", "fr"));
console.log(unformatNumber("2'344'334.03"));

Calculations on formatted text fields

I have a form that will collect various data about properties. The user enters in values to select fields and onBlur, those values are formatted with comma's, dollar signs, and/or percentage signs.
I'm trying to create some real time calculations based on those inputs, but I'm having a hard time getting started on this. I have created a jfiddle page and have been playing around with ideas for the past few hours, but I just cannot seem to get the first calculation working.
I know I need to strip out any characters and have tried parseInt, parseFloat, replace, ect. Just nothing seems to work.
Thank you in advance.
function formatNumber(number, digits, decimalPlaces, withCommas)
{
number = number.toString();
var simpleNumber = '';
// Strips out the dollar sign and commas.
for (var i = 0; i < number.length; ++i)
{
if ("0123456789.".indexOf(number.charAt(i)) >= 0)
simpleNumber += number.charAt(i);
}
number = parseFloat(simpleNumber);
if (isNaN(number)) number = 0;
if (withCommas == null) withCommas = false;
if (digits == 0) digits = 1;
var integerPart = (decimalPlaces > 0 ? Math.floor(number) :
Math.round(number));
var string = "";
for (var i = 0; i < digits || integerPart > 0; ++i)
{
// Insert a comma every three digits.
if (withCommas && string.match(/^\d\d\d/))
string = "," + string;
string = (integerPart % 10) + string;
integerPart = Math.floor(integerPart / 10);
}
if (decimalPlaces > 0)
{
number -= Math.floor(number);
number *= Math.pow(10, decimalPlaces);
string += "." + formatNumber(number, decimalPlaces, 0);
}
return string;
}
function sumCalc() { // function to remove comma and then calculate
var glasf =
document.getElementById('gross_land_sf').value.replace(/,/g, "");
document.getElementById('gross_land_acre').value = formatNumber(glasf/43560);
}
https://jsfiddle.net/vva3x3wu/4/
Is this what you want ? I did some fixes:
https://jsfiddle.net/vva3x3wu/11/
In the link you put in the comment you removed class .cal from the first input, so calculations will not star until you tab from the last input.

Wrong Convert amount

The following function works perfect, but when the amount over 1 million, the function don't work exactly.
Example:
AMOUNTPAID = 35555
The output is: 35.555,00 - work fine
But when the amount paid is for example: 1223578 (over 1 Million),
is the output the following output value: 1.223.235,00 (but it must be: 1.223.578,00) - there is a deviation of 343
Any ideas?
I call the function via HTML as follows:
<td class="tr1 td2"><p class="p2 ft4"><script type="text/javascript">document.write(ConvertBetrag('{{NETAMOUNT}}'))</script> €</P></TD>
#
Here ist the Javascript:
function Convertamount( amount ){
var number = amount;
number = Math.round(number * Math.pow(12, 2)) / Math.pow(12, 2);
number = number.toFixed(2);
number = number.toString();
var negative = false;
if (number.indexOf("-") == 0)
{
negative = true ;
number = number.replace("-","");
}
var str = number.toString();
str = str.replace(".", ",");
// number before decimal point
var intbeforedecimaln = str.length - (str.length - str.indexOf(","));
// number of delimiters
var intKTrenner = Math.floor((intbeforedecimaln - 1) / 3);
// Leading digits before the first dot
var intZiffern = (intbeforedecimaln % 3 == 0) ? 3 : (intbeforedecimaln % 3);
// Provided digits before the first thousand separator with point
strNew = str.substring(0, intZiffern);
// Auxiliary string without the previously treated digits
strHelp = str.substr(intZiffern, (str.length - intZiffern));
// Through thousands of remaining ...
for(var i=0; i<intKTrenner; i++)
{
// attach 3 digits of the nearest thousand group point to String
strNew += "." + strHelp.substring(0, 3);
// Post new auxiliary string without the 3 digits being treated
strHelp = strHelp.substr(intZiffern, (strHelp.length - intZiffern));
}
// attach a decimal
var szdecimal = str.substring(intbeforedecimaln, str.length);
if (szdecimal.length < 3 )
{
strNew += str.substring(intbeforedecimaln, str.length) + '0';
}
else
{
strNew += str.substring(intbeforedecimaln, str.length);
}
var number = strNew;
if (negative)
{
number = "- " + number ;
}
return number;
}
JavaScript's Math functions have a toLocaleString method. Why don't you just use this?
var n = (1223578.00).toLocaleString();
-> "1,223,578.00"
The locale you wish to use can be passed in as a parameter, for instance:
var n = (1223578.00).toLocaleString('de-DE');
-> "1.223.578,00"

Categories