jquery convert price from 5 decimals to round up to 2 decimals - javascript

I have a price number that looks like this: $27,272.70000
I'm trying to make it look like this: $27,272.70
I'm stuck with trying different methods but here is what i've got so far:
jQuery(document).ready(function() {
jQuery('.cart-table-wrapper #shopping-cart-table tbody > tr').each(function() {
var the_sp_subtotal = jQuery(this).find('td.col-total.a-right span.price').text().replace("$", "");
var new_sp_subtotal = parseFloat(the_sp_subtotal).toFixed(2);
console.log(new_sp_subtotal);
});
});
But the result that I get is: 27.00
Here is the fiddle - https://jsfiddle.net/zqe37xsk/1/
Can someone please help me, what I'm doing wrong?
Thank you

To format a currency string properly you could use the toLocaleString function. For this to properly work you have to transform your string into a float.
var price = '27,272.70000';
price = parseFloat(price.replace(/[$,]/g, ""));
console.log(price.toLocaleString('us-EN', {
style: 'currency',
currency: 'USD'
}));

parseFloat("27,272.70") returns 27 because the , in 27,272.70 is no longer part of a number.
As an alternative approach you could replace the part behind the last thousands separator and call toFixed on that. Then you can just join everything back together.
In your each function, use:
const [dollar, ...separatedNumber] = jQuery(this).find('td.col-total.a-right span.price').text().split(/\$|,/);
separatedNumber[separatedNumber.length - 1] = Number(separatedNumber.slice(-1)).toFixed(2);
console.log("$" + separatedNumber.join(","));

Related

Converting number string to comma version

I have a Angular 2 / Typescript application string that contains number representations such as the following...
10000
10000.50
-10000
-10000.50
0
I want to add in commas after the thousand mark, for example...
10,000
10,000.50
-10,000
-10,000.50
0
What is the best way to do this?
I have tried some other answers but nothing is quite right.
For example this.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); and this.value.toLocaleString(); don't seem to handle both the comman and decimal point.
Have you tried
var some_string_value = '-10000.50';
parseFloat(some_string_value).toLocaleString()
?
Use "indexOf('.')",splice to two part,then use the method you found.
function addComma(num){
//some type check here
var numStr = num.toString();
var intEnd = numStr.indexOf('.');
var onePart =numStr,otherPart ='';
if(intEnd !== -1){
var onePart = numStr.slice(0,intEnd);
var otherPart = numStr.slice(intEnd);
}
return onePart.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')+otherPart;
}
You can use a pipe, you can find a full answer to your question here: Add Comma Separated Thousands to Number Inputs in Angular2

Javascript: Most Efficient way to convert string to integer then back to string

I have a text input field which has a value of text to take in a string like "$2,000." In my functionality, I need to convert this back to a a number to run some mathematical functions and then spit it out back as another dollar value, which will be formatted like "$2,500.56" (I.E. not "$2,500.567"). Here's the two tests I've run so far:
var amount = "$2,000.58"
// "2000.58"
var amount_no_sym = amount.replace(/[^\d\.]/g, '');
//2000.58
var amount_integer = parseFloat(amount_no_sym);
//2000.58 (will cut out any additional decimal places)
var amount_decimals = amount_integer.toFixed(2);
//Final output is "$2,000.58" - the toLocaleString doesn't add back the , here?
var amount_dollar_string = "$" + amount_decimals.toLocaleString();
var amount = "$2,000.58"
// "2000.58"
var amount_no_sym = amount.replace(/[^\d\.]/g, '');
// 2000.58
var amount_integer = parseFloat(amount_no_sym);
//Final output is "$2,000.58"- but sometimes it will be something like "$3,564.345" for certain calculations.
var amount_dollar_string = "$" + amount_integer.toLocaleString();
Would the most optimal solution be to go to the second one, and then write a function to process a string and cut off the last number after the decimal if there are more than two....? Is there a simpler way and I'm doing too much work?
Thanks in advance!
Don't do your own number formatting. There's an API for that.
var formatter = new Intl.NumberFormat("en-us", { style: "currency", currency: "USD" });
console.log(formatter.format(2000.58));
In both cases you can avoid calling the function parseFloat() by using Unary + (plus) operator which attempts to convert the operand to a number, if it is not already. And to format currency you can also use Number.prototype.toLocaleString() passing as arguments the desired locale and an object with options:
var amount = '$2,000,344.58',
amount_integer = +amount.replace(/[^\d\.]/g, ''),
amount_dollar_string = amount_integer.toLocaleString('en-EN', {
style: 'currency',
currency: 'USD'
});
console.log(amount_integer);
console.log(amount_dollar_string);

Math Round Function

I'm using a form that use the following script to calculate the item price including VAT:
function calculateTotaleIVA() {
var tot = document.getElementById('totale').value;
document.getElementById('totale_prodotto').value = Math.round(tot*121)/100;
totale_prodotto.value = document.getElementById('totale_prodotto').value.replace(".", ",");
totale.value = document.getElementById('totale').value.replace(".", ",");
}
This function works fine but I have a questions. Some times the result is like this:
46,4
I want to see at screen two digits after point decimal like this:
46,40
How can I fix the above function to solve it?
Thanks in advance.
Use toFixed
(Math.round(tot*121)/100).toFixed(2)
you can use toFixed(2) for that
toFixed(No of digits)
(Math.round(tot*121)/100).toFixed(2);
see here

Javascript currency formatting

I'm having a pesky issue...
I'm using a small javascript to format currency such as
2990 to 2.990 and 129900 to 129.900 using the current line:
var wdiscount2 = wdiscount.toFixed(3);
However, when I have a number under 1000 such as 789 it displays like 0.789
Do you have a way for me to get around this easily?
Perhaps using a library, such as accounting.js from Joss Crowcroft is a good idea? It supports all kinds of formats and is used by quite a few people I believe.
wdiscount2 = accounting.formatMoney(wdiscount)
var wdiscount2 = wdiscount > 999 ? wdiscount.toFixed(3) : wdiscount;
It looks like the questions may already be answered, but there is another alternative, which might be interesting, namely use of regular expressions.
Example:
var num = 2990;
var formattedNumber = num.toString().replace(/(\d)(?=(\d{3})(?!\d))/g, "$1.")
A few test cases (num on the left, formattedNumber on the right):
2990 => 2.990
129900 => 129.900
789 => 789 (no . for this one)
I hope that will be helpful.
The best solution I've found is to use toLocaleString:
const formatCurrency = (num, locale = 'en-US', currency = 'USD', minimumFractionDigits = 2) => {
if (isNaN(num)) {
return num;
}
return num.toLocaleString(locale, {style: 'currency', currency, minimumFractionDigits});
};
Here is an example fiddle

How to append an extra 'Zero' after decimal in Javascript

Hye,
Iam new to javascript working with one textbox validation for decimal numbers . Example format should be 66,00 .but if user type 66,0 and dont type two zero after comma then after leaving text box it should automatically append to it .so that it would be correct format of it . How can i get this .How can i append ?? here is my code snippet.
function check2(sender){
var error = false;
var regex = '^[0-9][0-9],[0-9][0-9]$';
var v = $(sender).val();
var index = v.indexOf(',');
var characterToTest = v.charAt(index + 1);
var nextCharAfterComma = v.charAt(index + 2);
if (characterToTest == '0') {
//here need to add
}
}
Use .toFixed(2)
Read this article: http://www.javascriptkit.com/javatutors/formatnumber.shtml
|EDIT| This will also fix the issue if a user types in too many decimals. Better to do it this way, rather than having a if to check each digit after the comma.
.toFixed() converts a number to string and if you try to convert it to a float like 10.00
then it is impossible.
Example-
10.toFixed(2) // "10.00" string
parseFloat("10.00") // 10
Number("10.00") // 10

Categories

Resources