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.
Related
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)
I am currently trying to add two decimal places to the end of the number 1000 (I need it to be 1000.00)
I am trying to use: parseFloat(1000).toFixed(2) but it keeps returning a string. When I do parseFloat((1000).toFixed(2)) it returns a number, but gets rid of the decimal places. Is there a way to convert the number 1000 into the number 1000.00 without returning a string?
Try to use .toLocaleString()
var n = 1000;
var nWithZerto = n.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2});
Since, Javascript treat both integer and, decimal as Number, so it doesn't matter in calculation.
But, if you are printing it then only you require formatting and it can be done as (1000).toFixed(2)-> string.
I've seen multiple topics regarding this question, but none seem to answer it.
I want to round a number to two decimals, but without losing the function to use it in equations. So it shouldn't be transformed to a string. This DOES NOT work for what I want: parseFloat("50").toFixed(2)
Does anyone know how to parseFloat with 2 decimals as a number?
Just parse it back to a float.
parseFloat(Number(1.2345).toFixed(2)); //1.23
In javascript a number cannot have trailing zeros. 2.5 is a correct but 2.50 is not, this is why toFixed returns a string, not a number.
The best way to handle what you need is to store the number as a number and let it round out to whatever it needs. Only when showing the number on the screen should you do the toFixed(2) method to transforms it into a string.
// js
const price = 7.999999
const reducedPrice = price * 0.8
const finalReductionPrice = reducedPrice / 2.666666
// html
<p>price {price.toFixed(2)</p>
<p>reducedPrice {reducedPrice.toFixed(2)</p>
<p>finalReductionPrice {finalReductionPrice.toFixed(2)</p>
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).
I read some other's code, there is some piece of code below. I am wondering What does the method do with num?
formatNumber: function (num, digit) {
var pow = Math.pow(10, digit || 5);
return Math.round(num * pow) / pow;
}
BTW when I running
formatNum(11.267898, 5), it gave me 11.2679, is this OK?
Essentially, the function returns the number with certain precision. The precision is digit, which is 5 if not provided.
The return part essentially brings that many values (equal to digit) decimal right to left and then discard the rest and finally divides again to get the original value reduces to precision of digit.
Regarding BTW edit -
The value obtained is correct. See details below
When you call formatNum(11.267898, 5), you're asking the number to round to 5 digit precision and your number has 6 digit precision - precision is digits after the dot.
Now when you call num * pow the number becomes 1126789.8 and when you round this number, it rounds to closest integer which is 11.26790. Finally when you divide it by pow (100000), the number becomes 11.2679, discarding last 0 as trailing Zero in precision is pointless.
That is a really poor piece of code.
First, the naming conventions don't match what the code does at all.
The function name formatNumber() suggests that it formats a number. In other words, it ought to produce a string representation of a number, formatted in some way. But the function doesn't do this, it returns another number. That makes no sense. Numbers don't have a format, they are just numbers.
The parameter name digit sounds like it would contain a single digit. But it doesn't. It contains a count of digits that you want to round the number to. When you name things, singular and plural matter!
It gets worse.
As you found, the function doesn't even work. In your example, formatNum(11.267898,5) returns the number 11.2679. Why did it give you four digits when you asked for five? The result you were expecting was 11.26790, wasn't it? Well, of course that is identical to 11.2679, if we're talking about numbers. But what good does that do you when you wanted five digits?
Or to take a ridiculously simple example: formatNumber(1,2). You might expect that to produce 1.00, but it produces 1. Of course that is really the same value, but not formatted the way you want.
Now we go from the ridiculous to the sublime.
JavaScript has always had a built-in function that does exactly what we would expect formatNumber() to do: number.toFixed(digits). This does proper rounding and always returns the number of digits after the decimal point that you ask for. And of course, to be able to do that, it returns a string, not a number.
If we try these examples using .toFixed() they work as expected:
(11.267898).toFixed(5) returns the string "11.26790".
(1).toFixed(2) returns "1.00".
And so on, for just about anything you can throw at it. (It gives up on numbers with magnitude too large and uses exponential notation instead.)
Note that the parentheses around the first number in those examples are just needed to avoid a syntax error; in most cases you'd be using a variable and they would not be required, e.g.
myNumber.toFixed(2)
To summarize, not only does formatNumber() not do what it says and not anything useful, it was never needed in the first place!