Im using parseFloat on very high numbers or very low numbers.
The return value is like 123*10e15 , I need to be like 123*10^15 . 15 needs to be in upper writing as a pow.
Thanks.
parseFloat turns a string into a number. A number has no "format"; it gets turned back into a string (by Float's method toString) when you display it. If you want to display it with a caret, you will need to format (or reformat) it yourself into a string: easiest like this:
123e45.toString().replace('e', '*10^') // result: "1.23*10^+47"
(if the + bugs you, you can try this, using a regexp:)
123e-45.toString().replace(/e\+?/, '*10^') // result: "1.23*10^47"
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 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).
What I am trying to do is make an EV Track for Pokemon, you do not need to know what that is. Basically I want to add, for example, 3 into the attack input box, and 2 into defense and click submit, then 3 should appear in the grid under attack, and 2 under defense. Then if I put 1 in the attack input box, it should add 1 to the display in the grid.
But right now, instead of adding the numbers like numbers, it treats them as strings, and only adds them to the attack display.
Here is my code
http://pastebin.com/xy8232nG
Sorry if I do something wrong related ot the format of my question, just let me know, I'll fix it
So I added that parseint thing, and it works fine until I change the number or add 2 to attack and 2 to hp or something like that, it gives me "NaN" instead of a number
edit: so only the attack and special attack displays work, and if i input a value into any other stat, the special attack and attack values change to "NaN"
First off, you wrote defD as defF in your code by accident.
But more importantly, you are mixing strings and numbers. In Javascript, innerHTML returns a string. A string can be any piece of text, like "I am a jelly donut". It returns a string because innerHTML is capable of carrying more than numbers - it could contain text too. So innerHTML returns a string, just to be safe.
As such, you are trying to add a number to a string (piece of text) and you can't add a number to a sentence. So Javascript decides to treat the number like another piece of text rather than a number, and simply tacks the second number on the end of the first one rather than doing a mathematical equation.
Now many others have been saying "use parseInt, use parseInt!" and normally, that would work. That is because parseInt is a function that takes strings and converts them to numbers. However, when you start out, some of your textboxes are empty, so parseInt does not know what to do. So you get NaN (or, "Not a Number" to be exact) because the box is blank.
Usually, I avoid using parseInt because it is a function and in general, using plain math works faster and better than using a function in JS. An easy workaround to your problem is to to multiply the strings by one. Now, I know what you're thinking. "But if adding a number to text doesn't work, why does multiplying?" Simple. You cannot multiply text. As such, Javascript is forced to think of it like two numbers, rather than two strings.
atk += document.getElementById('atk').value*1;
spa += document.getElementById('spa').value*1;
def += document.getElementById('def').value*1;
spd += document.getElementById('spd').value*1;
hp += document.getElementById('hp').value*1;
spe += document.getElementById('spe').value*1;
document.getElementById("atkD").innerHTML = atk;
document.getElementById("spaD").innerHTML = spa;
document.getElementById("defD").innerHTML = def;
document.getElementById("spdD").innerHTML = spd;
document.getElementById("hpD").innerHTML = hp;
document.getElementById("speD").innerHTML = spe;
An added bonus is that this won't return NaN like parseInt does. Try it in your code and see.
(Note: you might want to use a for loop to loop through those and shorten your code instead. It isn't really necessary, but it would look nicer in your code.)
Use the parseInt function to make the values integers. Example:
.....
atk += parseInt(document.getElementById('atk').value);
.....
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).
I'm trying to extract specific numbers from a string but I'm not sure how to execute it.
The string is of the form:
center=43.571464,7.129565&zoom=12&size=480x225&markers=color:red%7Clabel:1%7C43.580293713725936,7.115145444335894&markers=color:red%7Clabel:2%7C43.56512073056565,7.121668576660113&sensor=false
The array I want is the marker coordinates near the end, specifically:
[43.580293713725936,7.115145444335894,43.56512073056565,7.121668576660113]
I thought I could pick these number out using their precision (15) but I don't know if that's best. I'm a hack when it comes to using regular expressions. Right now the best I've got is:
str.match(/[-+]?[0-9]*\.?[0-9]+/g)
But that just gives me all of the numbers.
Help much appreciated!
If your string is in str use this regex.
var coordinates = decodeURIComponent(str).match(/([\d.]{10,})/g);
http://jsfiddle.net/CHfcT/
You could try using the following regex
/\d+\.\d{7,}/g
This assumes that:
The marker coordinates always have 7 or more numbers after the dot
No other part of the string contains a similar pattern with more than 7 numbers after a dot
Example (JSFiddle):
str.match(/\d+\.\d{7,}/g);
The reason I picked 7 was because the other numbers in the sample had 6, so that excludes them. If you know that the coordinates always have a fixed number of decimal places, then you could just use that specific number without the , like this:
/\s+\.\d{10}/g