I get the value 17.000, 17 thousands.
var pay = document.getElementbyId("name").InnerHTML;
alert(pay);
it shows "17.000". But if I do like this:
var f = (pay * 24);
alert(f);
it shows 408, not 408.000. It makes 17 * 24 not 17.000 * 24. How to work around this?
The period is the decimal point in the English language. If you want "17.000" to be treated as seventeen-thousand and not seventeen, you have to remove the period:
var pay = +document.getElementById("name").innerHTML.replace(/\./g, '');
The unary plus (+) at the beginning converts the resulting string into a number. This is not strictly necessary in your example but can avoid problems in the long run.
Using parseFloat exposes the same problem as implicit type conversion.
If you want to format the number (i.e. convert it to a string with thousand separators) again, have a look at How to print a number with commas as thousands separators in JavaScript. Just use a period instead of a comma.
Related
I am trying to convert a string with more than 16 digit to number. But in javascript it is not allowed according to various article I read. Reference of some are here
How to convert a long string (more than 16 digits) into numbers
facing an issue with parseFloat when input is more than 16 digits
https://2ality.com/2012/07/large-integers.html
Below is the code I tried.
let x= "123456789123456789"
console.log(parseInt(x))
console.log(parseFloat(x))
console.log(Number(x))
console.log(+x)
let y= "1234567891234567.34"
console.log(parseInt(y))
console.log(parseFloat(y))
console.log(Number(y))
console.log(+y)
I want the exact numbers as I use string to display in ContentEditable field and when I save the data I need to pass it as a number. As it is related to banking the same numbers are important.
Is there any way I can solve this issue or any library I can use to solve this problem
try Use the BigInt, multiply with number or add,minus float number.
let x= "123456789123456789";
console.log(BigInt(x));
console.log(1*x);
let y= "1234567891234567.34";
console.log(0.01-0.01+y);
https://dev.to/sanchithasr/7-ways-to-convert-a-string-to-number-in-javascript-4l
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)
The question sprang up from reading the answers to this recent post.
The OP simply wants to know how to cut off a string at the second decimal point: e.g. '2.346' => 2.34
One of the users provided this answer:
function tofixed(str){
return parseInt(str * 1000 / 10) /100
}
I tested it with a very large number and got this result:
console.log(tofixed('53219247129812312132.453'))
//Result: 0.05
I got curios and started digging. The quirk seems to lie with parseInt, because I can easily run this:
console.log(53219247129812312132 * 1000 / 10)
OR
console.log("53219247129812312132" * 1000 / 10)
And get the proper result. But why do I get 5 when I run:
console.log(parseInt("53219247129812312132" * 1000))
It seems to always return the first character of the string. I thought perhaps the number is too large for parseInt to parse, but why, then can I parse this without any issues:
console.log(parseInt("5321924712981231213212323232323"))
That multiplication seems to throw parseInt for a loop when combined with a large number. Can someone explain this behavior to me?
What parseInt does is:
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
If the argument is not a string to begin with, it gets converted into a string.
When a large number is converted into a string, it starts with the most significant digit, followed by a . and eventually e:
console.log(String(53219247129812312132000));
console.log(parseInt(53219247129812312132000))
Since 5 is the starting "integer" part of the string before the dot, that's the result. (The engine stops trying to parse the string once it encounters the dot, since it considers characters past that to not be part of the integer part of the number.)
Good day,
In my java action file, I have a list:
protected ArrayList< String > deletedCorpRegisteredAccountRefNo = new ArrayList< String >( );
And then I put in some data inside this ArrayList, and print it out:
System.out.println( "deletedCorpRegisteredAccountRefNo : "+
deletedCorpRegisteredAccountRefNo );
And the result display correctly:
deletedCorpRegisteredAccountRefNo : [0000000000000234324, 0000000000015422629]
Then I go to my jsp and my javaScript function, I tried to assign this ArrayList value to a var call refNoList, and print out:
var refNoList = ${actionBean.deletedCorpRegisteredAccountRefNo};
console.log(refNoList);
I am expected I will see my browser console will print out something like what I see in Java System.out.println(), but I get another result:
[80084, 15422629]
The 15422629 is still acceptable, because maybe JavaScript auto trim the 0. But not understand why 0000000000000234324 will become 80084, this is totally different.
I try to google to find what is the root cause, but fail to get it, I think I am asking the wrong question in Google.
Kindly advise.
If a JavaScript number starts with zero, it can be interpreted as an octal value. And
var x = 0234324;
console.log(x);
this writes out 80084, because in decimal, this is the same value, as 234324 in octal.
You need to trim the trailing zeroes from the strings, and it will work as you want it to.
Other number definitions
In JavaScript the numbers can be interpreted as binary, octal, decimal or hexadecimal. Here a little list of different literals:
123 - normal decimal
0123 - octal: decimal value is 83
0x123 - hexadecimal: decimal value is 291
0o123 - octal: decimal value is 123
0b101 - binary: decimal value is 5
The problem with the second example (0123) is that it is only interpreted as octal when it is possible. E.g. 09123 and 081 will be interpreted as decimal. Moral of the story, you should not depend on this behaviour, if you need an octal, use 0o explicitely, if you need decimals, trim those zeroes.
Fixing the issue
To parse the number as a decimal, no matter what, you can simply give the radix value as a parameter to parseInt(number, radix):
var x = "000000123";
console.log(parseInt(x, 10)); // prints out 123
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