Problems with JavaScript "parseInt()" decimal string - javascript

I get the total_amount in cart code of ecommerce web page, after I use toString function, but when I convert the 14.82 string to int number, the decimals disappear.
<script>
var total_amount_string = <?=json_encode($cart['total_pvp'])?>;//-> 14,82
var total_amount_int = parseInt(total_amount_string).toFixed(2); //-> 14.00(here is the error)
console.log(total_amount_string) //-> 14,82
console.log(total_amount_int) //-> 14.00
</script>
What's the matter?

If the input string is "14,82" and you want the value 14.82, you'll need to convert the , to a . and then use parseFloat:
var total_amount_int = parseFloat(
total_amount_string.replace(/,/g, ".")
).toFixed(2);
parseInt will only parse the leading part of the string that defines a whole number ("int" = "integer" = "whole number"), so it stops at the ,. parseFloat will parse a decimal number, but only understands . as the decimal point, not ,, even in locales where , is the decimal point.

you should use parseFloat() instead of parseInt(). Because integer number is not decimal.

An integer has no decimal part, so any number "casted" to int will lose its decimals. You should use parseFloat if you want to keep the decimal part.
On the other hand, make sure you are not using a comma: Javascript parse float is ignoring the decimals after my comma

Your number is using a "," separator. Unfortunately there is no locale settings for number parsing in JavaScript, so you are forced to a bit more hacky:
var total_amount_string = "14,823462";
var total_amount_float = parseFloat(total_amount_string.replace(",", ".")).toFixed(2);
document.getElementById("total_amount_string").innerText = total_amount_string;
document.getElementById("total_amount_float").innerText = total_amount_float;
total_amount_string: <span id="total_amount_string"></span>
<br />
total_amount_float: <span id="total_amount_float"></span>

The parseInt() function parses a string and returns an integer. ParseInt returns only the first number in the string is returned!. If the first character cannot be converted to a number, parseInt() returns NaN.

Related

String To Number Confusion

Why does parseInt("-1000-500-75-33") return -1000?
Shouldn't it return the sum of those numbers: -1608
How can I get the string "-1000-500-75-33" to return as the sum of those numbers?
parseInt will try to get a number starting from the beginning of the string.
Since - is a valid character to begin a number with, it parses the string until it finds something invalid. The second - is invalid because no integer can contain an - inside it, only digits. So it stops there and considers the number to be "finished".
Now, if you want to process the expression, you can use eval like so:
eval("-1000-500-75-33")
This will return -1608 as expected.
parseInt will not perform any computations, rather it will try to convert a string into an integer. It returns -1000 because the dash afterwards would not be considered a valid number. If you want to sum all these numbers you could split on the dash, map to Number, then reduce:
var numString = "-1000-500-75-33";
numString.split('-').map(e => Number(e)).reduce((a, b) => a - b);
Try to eval! it's safe here
eval("-1000-500-75-33").toString()
console.log(eval("-1000-500-75-33").toString());
And about type casting: After parsing -1000, which is obviously "negative 1000", It will escape casting as soon as it detect a symbol common between numbers & strings. So parseInt is seeing "-1000-500-75-33" as "-1000NotConvertableString", So left the remaining away, returning -1000 as the result of type-casting.
Since they are in a string, ParseInt does not parse the whole string, just finds the first applicable number from the start & returns it. If the start of the string cannot be parsed, it returns NaN
parseInt("-1000NOT_NUMBER") = -1000
parseInt("test-1000`) = NaN
You have to use eval function to do what you want, that evaluates given string as if it were a command entered into the console;
eval("-1000-500-75-33") = -1608

Javascript: using toLocaleString + Tofixed

I need to format a number for a project im working on at work, only problem is that I cant format it how i want.
I convert the number to a localestring using the toLocaleString method which gives me the commas but i also need decimal places, nothing i seem to do works.
var number = 123.322
number = parseFloat(number).toFixed(2) //123.22
number.toLocaleString() //123.22
The above code just returns the parsefloated number along with the tofixed decimal values but it doesn't add the commas.
How do i get a number to have two decimal places (when the value is 'xx.00') and also be comma separated. Is this possible in JavaScript?
You can give an object to .toLocaleString() which describes what you want:
var sNumber = (10123.322).toLocaleString(undefined,
{'minimumFractionDigits':2,'maximumFractionDigits':2});
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Original:
const fNumber = 10123.322;
const sNumber = parseFloat(fNumber.toFixed(2)).toLocaleString();
console.log(sNumber);
The number is already in decimal/float format on the first line.
.toFixed(2) turns it into a string using fixed-point notation.
parseFloat() takes that string and turns it back into a float.
.toLocaleString() turns it into a string using the local format.
Just to do it in one line
var num = '12233.3366554';
num = parseFloat(parseFloat(num).toFixed(2)).toLocaleString('en-IN', { useGrouping: true });
Yes, it is possible using .toLocaleString, yo just need to specify the language, optionally you can specify decimals and currency. look at this example:
35000.2455.toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2,style: 'currency', currency: 'USD' })
this returns $35,000.25
Number.toLocaleString works on a number, but toFixed returns a string.
Coerce the string back into a number first
var number = 123.322;
var string = parseFloat(number).toFixed(2);
var parsed = (+string).toLocaleString();
console.log(parsed);
In order to get commas you have to specify the locale .The locale en includes commas for the numbers. toFixed() Returns a string. toLocaleString() function commas works on a number not on a string.So parse the string to float.
var number = 1234567.322;
number = parseFloat(parseFloat(number).toFixed(2)).toFixed(2) ;
number=number.toLocaleString('en');
toLocaleString function provide number representation based on languages
var number = 3500.00;
if(Number.isInteger(number)){
var zeroappend= number.toLocaleString()+".00";
console.log(zeroappend);//3,500.00;
}else{
console.log(number.toLocaleString());
}

Javascript format number of decimal places in float

Can anybody help me with this issue i'm having? I'm using the following code to get the value of an input field
parseFloat($("#salaryFrom").val());
The only problem is that if the value in the salaryFrom field ends with a 0 it's getting cut of from the results. e.g. The value 8.50 is being returned as 8.5 and I need it to return 8.50
As a float 8.50 an 8.5 are identical. However when you convert your number to a string you can specify the number of decimal places you would like to use with the function toFixed() e.g.
var a = parseFloat($("#salaryFrom").val());
var b = a.toFixed(2);
The function toFixed() takes the number of decimal places you would like to format your number to, in this case 2.
Javascript has a toFixed() function to format floats. So do try that.
tmp = parseFloat($("#salaryFrom").val());
formatted_val = tmp.toFixed(2);
alert(formatted_val);
Use .toFixed(2) in javascript. (2) - its optional The number of digits after the decimal point. Default is 0 (no digits after the decimal point)
var num = 8.5;
console.log(num.toFixed(2))
Example: Using toFixed
var numObj = 12345.6789;
numObj.toFixed(); // Returns '12346': note rounding, no fractional part
numObj.toFixed(1); // Returns '12345.7': note rounding
numObj.toFixed(6); // Returns '12345.678900': note added zeros
(1.23e+20).toFixed(2); // Returns '123000000000000000000.00'
(1.23e-10).toFixed(2); // Returns '0.00'
2.34.toFixed(1); // Returns '2.3'
-2.34.toFixed(1); // Returns -2.3 (due to operator precedence, negative number literals don't return a string...)
(-2.34).toFixed(1); // Returns '-2.3' (...unless you use parentheses)

Get all numbers from string, with decimals

I need to convert 'KM1+000.321' to 1000.321.
I tried this
var string = 'KM1+000.321';
console.log(parseInt(string.replace(/\D/g, ''), 10)) //1000321
But that also removes the decimal. How do I write an expression that keeps the decimal?
http://jsfiddle.net/bbn80knc/
Assuming that there will only be one decimal, this will work:
var string = 'KM1+000.321';
console.log(parseFloat(string.replace(/[^\d.]/g, ''))) //1000.321
Note, you need to use parseFloat, not parseInt, to get the decimals.
To replace all but the digits and the decimal dot with nothing, use
string.replace(/[^\d.]/g, '')
To convert to a number with a fraction, you can't use parseInt() but parseFloat():
parseFloat(string.replace(/[^\d.]/g, ''))

How to get numerical value from String containing digits and characters

Is there any built in method to get which can parse int from string ("23px")?
I know I can use substring and then parseInt but I want to know if there is any other way available to do this.
parseInt will grab the first set of contiguous numbers:
parseInt('23px');
returns 23.
If there is any chance there will be leading zeros, use a radix:
parseInt('23px', 10);
which is a good habit in general.
parseInt can do it. Just use:
var num = parseInt("23px", 10);
It will parse the integer part and ignore the rest.

Categories

Resources