Javascript Operators Issue working with Decimals - javascript

I got everything almost where I want it. My only problem is that for some reason I can't get the bctf1 to add right. Say if bctf = 10, the result with the code would be 100.59 instead of 10.59. Say if bctf = 25, the result with the code would be $251.03 instead of 26.03.
// BUY TOTAL
<script type="text/javascript">
function buytot(){
var bctf = document.getElementById('buyctf').value;
if(bctf.charAt(0) == "0" || bctf.charAt(0) == "" || bctf.charAt(0) == " "){
bctf2 = "0.00";
} else {
pcbctf = bctf*.029;
pcplusc = pcbctf+.30;
bctf1 = bctf+pcplusc;
bctf2 = Math.round(bctf1*100)/100;
}
document.getElementById('buyctotal').innerHTML = bctf2;
}
</script>
Here's the HTML with JS -> http://jsfiddle.net/hhWDe/5/

Force a data type on this:
var bctf = parseFloat(document.getElementById('buyctf').value);

You need to convert the String values returned by the element value properties into numbers. Something like this:
var bctf = Number(document.getElementById('buyctf').value);
// OR
var bctf = parseFloat(document.getElementById('buyctf').value, 10);
Also, consider using the "toFixed" number method to get the ".00 decimal places for whole dollar amounts:
var oneDollar = 1;
oneDollar; // => 1
oneDollar.toFixed(2); // => "1.00"

You can add "+" to convert a value to an integer (or float).
It will take any string and convert it, if the string cannot be converted, it will return NaN:
So your script would look like the following:
var bcft = +document.getElementByID('buyctf').value;

Thank You all :) This is the working code. I add bctf0 = Number(document.getElementById('buyctf').value); after the else and everything worked fine.
// BUY TOTAL
function buytot(){
var bctf = document.getElementById('buyctf').value;
if(bctf.charAt(0) == "0" || bctf.charAt(0) == "" || bctf.charAt(0) == " "){ bctf2 = "0.00";
} else {
bctf0 = Number(document.getElementById('buyctf').value);
pcbctf = bctf0*.029;
pcplusc = pcbctf+.30;
bctf1 = bctf0+pcplusc;
bctf2 = Math.round(bctf1*100)/100;
}
document.getElementById('buyctotal').innerHTML = bctf2;
}

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

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"));

js function ignores Decimal Numbers

So i made a function that calculate the price by multiplication how many meters i put the problem is when ever i put decimal numbers it ignores it
heres my script
<script>
function getFillingPrice() {
cake_prices = document.getElementById('price').value;
filling_prices = document.getElementById('test2').value;
var t=parseInt(filling_prices);
var x=parseInt(cake_prices);
return t*x;
}
function calculateTotal() {
var total = getFillingPrice();
var totalEl = document.getElementById('totalPrice');
document.getElementById('test3').value =total + " دينار ";
totalEl.style.display = 'block';
}
</script>
You're converting the values to integers when you get them from the DOM.
Change this...
var t=parseInt(filling_prices);
var x=parseInt(cake_prices);
to this...
var t=parseFloat(filling_prices);
var x=parseFloat(cake_prices);
Beside the parsing problem, you could use
an unary plus + and
a default value for non parsable value, like letters or an empty string (falsy values) with a logical OR ||.
cake_price = +document.getElementById('price').value || 0
// ^ unary plus for converting to numbner
// ^^^ default value for falsy values
Together
function getFillingPrice() {
var cake_price = +document.getElementById('price').value || 0,
filling_price = +document.getElementById('test2').value || 0;
return cake_price * filling_price;
}

Temperature Converter (IF ELSE conditions) in JavaScript

I am creating a Temperature Converter out of JavaScript. So far only the Celsius conversion works when the user inputs that first. I am just having trouble figuring out how to structure the other if statements.
var conversionC;
var conversionF;
var conversionK;
if ( celsius.value != "" ) {
conversionF = document.getElementById("celsius").value * 9 / 5 + 32;
document.getElementById("fahrenheit").value = Math.round(conversionF);
}
else if ( fahrenheit.value != "" ){
conversionC = (document.getElementById("fahrenheit").value - 32) * 5 / 9;
document.getElementById("celsius").value = Math.round(conversionC);
}
if ( kelvin.value != "" ){
conversionC = document.getElementById("celsius").value - -273;
document.getElementById("kelvin").value = Math.round(conversionC);
}
I only want to keep the one Convert button that I have, and still have it work when the user decides to input a Fahrenheit or Kelvin first.
Any guidance is greatly appreciated!
Here is a JSFiddle of my program so far:
https://jsfiddle.net/2sharkp/kw2sr1wx/
Thanks!
In your JSFiddle, you are taking each value and converting it into a float with parseFloat.
This means that when you hit if ( celsius.value != "" ), you are calling .value on a number, which is undefined. So you're really calling if ( undefined != "" ), which is true, and your first if block will always execute.
I'm assuming that your intention is to take the most recently edited field and use that for the conversion. I would recommend using a flag to indicate which field was last edited.
https://jsfiddle.net/camEdwards/chyg4ws1/
<script>
let cels = document.getElementById('cels');
let fahr = document.getElementById('fahr');
cels.addEventListener('input', function(){
let f = (this.value * 9/5) +32;
if(!Number.isInteger){
return f.toFixed(2);
}
fahr.value = f;
});
fahr.addEventListener('input', function(){
let c = (this.value - 32) * 5/9;
if(!Number.isInteger){
return c.toFixed(2);
}
cels.value = c;
});
</script>

Move comma position JavaScript

I'm trying to move the position of the comma with the use of JavaScript. I have managed to remove all the parts of the string I needed removing. The only problem is that the comma is in the wrong position.
The current outcome is 425.00, but I simply want '42.50'
success: function(result) {
if (result != '') {
alert(" "+result+" ");
}
var discountVal = result.replace(/\D/g,'');
newDiscountVal = discountVal.replace(7.50, '');
$("input#amount").val(discountVal);
}
I am grabbing database echo values with a combination of string and echo - numbers..
You could divide by ten, then convert back to a String using toFixed(2) which forces formatting of 2 decimal places
Javascript allows implicit conversion of Strings to numbers, by firstly converting the String to a Number so it is valid to divide a String by a number.
var input= "4250.00";
var output = (original / 100).toFixed(2); // => "42.50"
Note this method has different behaviour due to rounding. Consider the case 9.99. If you use a string manipulation technique you'll get ".99", with divide by 10 method above you'll get "1.00". However from what has been said in comments I believe your inputs always end .00 and never anything else, so there will be no difference in reality.
If it is number you can just divide by 10
If it is string you can do like this:
var ind = text.indexOf('.');
text = text.replace('.', '');
text.slice(0, ind-1) + '.' + text.slice(ind-1, text.length)
Here is a solution:
function moveComma(val, moveCommaByInput) {
if (val || typeof val === 'number') {
const valueNumber = Number(val);
const moveCommaBy = moveCommaByInput || 0;
if (isNaN(valueNumber)) {
return null;
} else {
return Number(`${valueNumber}e${moveCommaBy}`);
}
}
return null;
}
This is how i solved it..
var discountVal = result.replace(/\D/g, '');
var newDiscountVal = discountVal.replace(7.50, '');
var lastDigits = newDiscountVal.substr(newDiscountVal.length - 2);
var removedDigits = newDiscountVal.slice(0,newDiscountVal.length - 2);
var discountRealValue = removedDigits + '.' + lastDigits;
$("input#amount").val(discountRealValue);
Cheers

Categories