Multiplcation in Javascript - javascript

I have a script for taking data entered into a Price field on my editor and splitting it across a Pounds and Pence field based on the . symbol.
Now I've been asked if I could multiply the Price field by 1.2 and display the result in the Pounds field. The pence field would no longer be needed.
I have no idea if multiplication can even work and especially using decimal points... Can anyone explain how I should rewrite the below?
$('#price1').keyup(function(event) {
if ($('#price1').val().indexOf('.') != -1){
$('#pence1').val($('#price1').val().substr($('#price1').val().indexOf('.') + 1, $('#price1').val().lengh));
$('#pound1').val($('#price1').val().substr(0, $('#price1').val().indexOf('.')));
}else{
$('#pound1').val($('#price1').val());
};
});

Some things to remark:
Your current solution has a spelling mistake for length.
Don't locate the decimal point. Instead use native JavaScript capabilities to evaluate the input. You can use parseFloat(), Number() or the unary plus operator for that.
Once you have the numeric value, you can multiply using the * operator. As multiplication will also convert its operands to number, you don't even need the previous advice, although it is still good practice to first do the conversion to number and then do the arithmetic.
Use the input event instead of the keyup event: input is not always the result of key events (think copy/paste via context menu, drag/drop, other devices...)
Here is the proposed solution:
$('#price1').on("input", function(event) {
var num = +$('#price1').val(); // convert to number using unary plus operator
// multiply, format as string with 2 decimals, and convert back to number
num = +(num * 1.2).toFixed(2)
$('#pound1').val(num); // output
});

Related

How can I handle float number correctly in JS?

In JS, I do have a float number which come from php as below:
var number = 2,206.00
In JS, I need to use parseFloat that number.
So I tried parseFloat(number), but its give only 2. So how can I get 2206.00 instead of 2?
Number.parseFloat is the same function object as globalThis.parseFloat.
If globalThis.parseFloat encounters a character other than:
a plus sign or,
a minus sign or,
a decimal point or,
an exponent (E or e)
...it returns the value up to that character, ignoring the invalid character and characters following it. A second decimal point also stops parsing.
So the following prints 2. And this seems to be your problem.
console.log(parseFloat('2,206.00')) // 2
Solution: use string manipulation to remove any commas from the number (really a String before parsing it.
console.log(parseFloat('2,206.00'.replaceAll(',', ''))) // 2206
If you need to store the value as a number but render it as a formatted string, you may need Number#toFixed to render the values after the decimal point:
console.log((2206).toFixed(2)) // '2206.00'
Final note: be careful about localization because some countries use commas for decimal points and decimal points for number grouping. As #t.niese says: store number values without localization, and then apply localization at the surface of your app. But that is a wider, more complicated topic.
You have to remove comma first and use parseFloat.
And about 2 decimal after dot, I see you use number_format($myNumber, 2) in PHP, so in JS, you use .toFixed(2).
var number = '2,206.00';
var result = parseFloat(number.replace(/,/g, '')).toFixed(2);
console.log(result);
First of all what you currently have most probably would trigger an Unexpected number error in JS.
It seems the generated value comes from the number_format() PHP function which returns a string. Moreover the var number variable should also be considered a string as we have a string format.
So firstly you should quote var number = '2,206.00' after that, you have to make the string float-like in order to parse it as float so we should replace , with empty string in order for the number to become 2206.00 number = number.replace(",",""). Lastly the parse should be done now in order to convert the float-like string to an actual float parseFloat(number).
Whole code:
var number = '2,206.00';
number.replace(",","");
number = parseFloat(number);
ok, basically you want a two decimal number after point like (20.03),
try this
parseFloat(number).toFixed(2)

problem with parsing numbers using JQuery

i have a Javascript file that calculates and parse the rows in a crm module called jobs.
I have function called recalculateSummary that calculate the price like this
I want it to show 3,578.00 in total like Line Total
The problem is the function parseFloat i think it ignores the ',' as i want if i write 3,578.00 the total should be 3,578.00.
I was able to achive this by removing parseFloat function and removing the ReplaceAll function but i got error when i add more rows the total value becomes 0.00.
recalculateSummary: function(){
var subtotal = 0;
$.each($('.row_line_total'), function(index,value){
lineTotal = $(value).html().replaceAll(',','.').replaceAll(' ','');
subtotal += parseFloat(lineTotal);
});
i know the question isn't clear but i need some help
Are trying to add toFixed(2) for calculation result?
I mean this:
$('.summary_subtotal').html($.number(subtotal,2));
->
$('.summary_subtotal').html($.number(subtotal.toFixed(2),2));
The reason is that by replacing the comma with the dot, parseFloat will interpret that as the decimal separator and so your number suddenly is a factor of 1000 smaller.
Take for example 3,578.00
Your code will grab that value as a string with $(value).html().
This is OK, although it would be better to do $(value).text() as
you are not really interested in HTML encoding, but plain text.
Then the code performs a disastrous replacement with
.replaceAll(",", "."). This will turn the string to "3.578.00"
(Not good!).
Finally the code converts this string to number with parseFloat.
The first dot is interpreted as decimal separator, not as thousands
separator (which it originally was). The second dot cannot be
interpreted as part of the number, and so parseFloat returns a
number with value 3.578. You probably have some other mechanics in
place to only display 2 decimal digits, so this value ends up on the
page as 3.58 (rounded).
In order to fix this problem, replace this:
lineTotal = $(value).html().replaceAll(',','.').replaceAll(' ','');
with:
lineTotal = $(value).text().replace(/[^.\d]/g, '');
Here we remove anything that is neither a dot (.), nor a digit (\d), using a regular expression: [^.\d]. So now the example value will become "3578.00" (the thousands separator is removed). parseFloat will turn this string into the number 3578. Your rendering mechanics will possibly render that with two decimals and a thousand separator as 3,578.00
All in all it is better to write your logic based on numeric variables and only use the DOM elements for output, not to read values from it (which are already formatted).

Remove currency symbol from string and convert to a number using a single line in Javascript

I have a string below that is a price in £, I want to remove the currency symbol and then convert this into a number/price I can use to compare against another value (eg. X >= Y ...)
£14.50
I have previously converted strings to numbers used for currency with
var priceNum = parseFloat(price);
IDEAL OUTCOME
14.50 as a number value. Can this be done in a single line?
I found this very helpful
var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9\.-]+/g,""));
Convert (Currency) String to Float
If the currency symbol will always be there, just use substring:
var priceNum = parseFloat(price.substring(1));
If it may or may not be there, you could use replace to remove it:
var priceNum = parseFloat(price.replace(/£/g, ""));
Beware that parseFloat("") is 0. If you don't want 0 for an empty input string, you'll need to handle that. This answer has a rundown of the various way to convert strings to numbers in JavaScript and what they do in various situations.
Side note: Using JavaScript's standard numbers for currency information is generally not best practice, because if things like the classic 0.1 + 0.2 issue (the result is 0.30000000000000004, not 0.3). There are various libraries to help, and BigInt is coming to JavaScript as well (it's a Stage 3 proposal at the moment, currently shipping in Chrome). BigInt is useful because you can use multiples of your basic currency (for instance, * 100 for pounds and pence).
try this number-formatter-npm library. This library is fantastic.
npm i number-formatter-npm
documentation:https://www.npmjs.com/package/number-formatter-npm

Rounding a figure retrieved from html using javascript and jquery

I am having a little problem with rounding numbers which are brought in from html.
For example a value extracted from <input id="salesValue"> using var salesValue = $("salesValue").val() would give me a text value.
So if I did something like var doubleSalesValue = salesValue + salesValue; , it would return the number as a concatenation instead of summation of the two values.
I could use var doubleSalesValue = salesValue * 2.0; which does return the value which is to multiple decimal places. However, if I did want to use the other method, how can I approach the situation.
What methods do you use? I have created a function which I run on each number where I want to restrict the decimal places along with converting the type to number
function round(number, figure){
return Number(Number(number).toFixed(figure));
}
I have to run Number initially to make sure that the value is converted to type number and has the method toFixed, otherwise it would throw an error here. Then I have to round the number again to the number of decimal places as required by the function, and somehow after running the toFixed method the number would sometimes turn to a string.
So, I decided to run the Number function Number(number).toFixed(figure)
Is there anything else or any different paradigm that you follow?
EDIT: I want to know if what I am doing here is conventional or are there better methods for this in general?
If you want to round it to 2 decimals you can simply do this:
var roundedNum = Math.round(parseFloat(originalNum) * 100) / 100;
Regarding your question:
and somehow after running the toFixed method the number would sometimes turn to a string.
I suggest next time read the dox a bit better https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed which says:
Returns
A string representation of number that does not use exponential
notation and has exactly digits digits after the decimal place. The
number is rounded if necessary, and the fractional part is padded with
zeros if necessary so that it has the specified length. If number is
greater than 1e+21, this method simply calls
Number.prototype.toString() and returns a string in exponential
notation.

correct number format detection separator

I have
var value = $120,90
var value = $1,209.00
currently I replace the first case with
value = value.replaceAll(",", ".").replaceAll("[^0-9.]*", "");
which gives me that I am looking for: the integer 12090
with the second case I run in a problem however like this. How can I solve this in Javascript?
You may modify you regexp.
value = value.replace(/,/g, ".").replace(/^\D|\.(?!\d*$)/g, "");
First will replace ',' to '.' and the 2nd replace NON-digit symbols in the beginning of the string and all dots EXCEPT the last one with the empty string. Then use parseFloat.
To be sure completely it's better to create a template for data input and don't allow users to enter values in an invalid format.
I cannot see how you can make an algorithm work unless you insist that everyone enters dollars and cents. The only option I can think of is to use locale to determine the number separator.
Could you use the answer from this thread?
How can I remove the decimal part from JavaScript number?
They use Math.floor() (round down), Math.ceil() (round up) or Math.round() (round to nearest integer).

Categories