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)
Related
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'm looking to add decimals to the end of my integer. As an example:
15 => 15.00
The problem with methods like toFixed is that it will convert it into a string. I've tried to use parseFloat() and Number() on the string, but it'll convert it back to an integer with no decimals.
Is this possible? If not, can someone explain to me the logic behind why this isn't possible?
EDIT: Welp the intent was to display the number as a number, but from the going consensus, it looks like the way the only way to go about it is to use a string. Found an answer on the why: https://stackoverflow.com/a/17811916/8869701
The problem you are finding is that all numbers in javascript are floats.
a = 0.1
typeof a # "number"
b = 1
typeof b # number
They are the same.
So there is no real way to convert to from an integer to a float.
This is the reason that all of the parseFloat etc are string methods for reading and writing numbers from strings. Even if you did have floats and integers, specifying the precision of a number only really makes sense when you are displaying it to a user, and for this purpose it will be converted to a string anyway.
Depending on your exact use case you will need to use strings if you want to display with a defined precision.
When working with numbers 15 and 15.00 are equal. It wouldn't make any sense to use memory to store those trailing or leading zeros.
If that information is needed it is usually for displaying purposes. In that case a string is the right choice.
In case you need that value again you can parse the string as a number.
There are a few Javascript functions available to convert anything into its equivalent number. Number() operates on an Object, valueOf(), parseFloat, parseInt() are also available.
I have an array which stores numbers 0-9 and decimal point, the elements of the array taken together represents a number. What is the best way to convert this array into a number, whole or fractional?
EDIT: Apologies if I were not clear before. The array, holding the 0-9 characters and possibly a decimal point, could represent either a whole number(without the decimal obviously) or a fractional number. So please suggest something that works for both cases. Thanks.
Try this
var a = [1,2,3,".",2,3];
var num = +a.join("");
What is the best way to convert this array into a number, whole or fractional?
Firstly to combine your array elements you should use Array.join().
You will then have a concatenated variable of your values and decimal. To convert this to a whole number, use parseInt(), and to a floating point number use parseFloat(). You can use the unary + operator (which acts similarly to parseFloat), however in my opinion it is not the best choice semantically here, as you seem to want a specific type of number returned.
Example:
var arr = ['1','.','9','1'];
var concat = arr.join();
var whole = parseInt(concat);
var floating = parseFloat(concat);
Also, parseInt will trim the decimal portion of your number, so if you need rounding you can use:
var rounded = Math.round(parseFloat(concat));
You could use the split property of the string. It splits all the characters into an zero based array.
var charSplits = "this is getting split.";
var splitArr = charSplits.split();
Console.log(splitArr);
// this returns i
Console.log(splitArr[2]);
I am attempting to develop a conversion website that takes a numeric value:
1,200.12
or
1.200,12
or
1200.12
or
1200,12
and have them all interpreted as 1200.12 by parseFloat.
I would also like decimals to be able to be interpreted.
0.123
or
0,123
as 0.123
through a textarea and then parseFloat the number in order to perform calculations.
These are the results I am getting:
textarea input = 12,000.12
value after parseFloat = 12
Does parseFloat not recognize the formatting of the numbers?
i get the same results with:
textarea input: 12.000,12
value after parseFloat = 12
How do I solve this problem? It would seem I need to strip out the commas since parseFloat doesn't read beyond them and with european notation strip the decimals and change the comma to a decimal for parseFloat to read the input correctly. Any ideas on how to solve this? My guess is I would need to identify the string input as either european or american decimal notation and then perform the required actions to prepare the string for parseFloat. How would I go about achieving that? All contributions are appreciated. Using HTML5 and Javascript. This is my first website so please go easy on me.
Best,
RP
To all contributors...Thank you! So far all the input has been sweet. I don't think we are going to be able to use a single replace statement to correctly strip both european and american notation so I think I should use REGEX somehow to determine the notation and then split into an if else statement to perform separate replace functions on each individual notation.
var input, trim;
input = "1.234,56" //string from textarea on page
if(/REGEX that determines American Notation/.test(input){
trim = input.replace(/\,/,"");//removes commas and leaves decimal point);
}
else(/REGEX that determine European Notation/.test(input)/){ //would qualify input here
rep = input.replace(/\./,"");//removes all decimal points);
trim = rep.replace(/\,/,"."//changes the remaining comma to a decimal);
}
//now either notation should be in the appropriate form to parse
number = parseFloat(trim);
Is this possible using REGEX? Please see my other question.
Regex - creating an input/textarea that correctly interprets numbers
One way would be to strip the comma signs, for example with:
.replace(",", "")
From there you should be able to parseFloat
Updated with fiddle: http://jsfiddle.net/aLv74xpu/2/
Here is a solution that uses a regular expression to eliminate all commas and all periods, except the last one.
var number = "1,234.567.890";
var replaced = number.replace(/,|\.(?=.*\.)/g, "");
var result = parseFloat(replaced);
// result === 1234567.89
Alternatively, you can use this, which treats commas and periods identically, and ignores them all except for the last one.
var number = "12.345,67";
var replaced = number.replace(/[.,](?=.*[.,])/g, "").replace(",", ".");
var result = parseFloat(replaced);
// result === 12345.67
parseFloat parses its argument, a string, and returns a floating point
number. If it encounters a character other than a sign (+ or -),
numeral (0-9), a decimal point, or an exponent, it returns the value
up to that point and ignores that character and all succeeding
characters. Leading and trailing spaces are allowed.
From the good MDN network: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
So it is the expected behaviour of parseFloat
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.