i am using eval to convert string decimals to decimals.
eval("000451.01");
When i am using the above statement javascript it throws exception 'expected ;'
and when using eval("000451"); it gives me a different result.
anyone has got any idea??
You should not use eval to parse numbers; it will be orders of magnitude slower than normal methods.
Instead, you should use the parseFloat function. like this: parseFloat("000451.01").
The reason you're getting the error is that Javascript treats numbers that begin with 0 as octal numbers, which cannot have decimals.
If you want to parse an integer, call parseInt, and make sure to give a second parameter of 10 to force it to parse base 10 numbers, or you'll get the same problem.
In Javascript, a token starting with zero is an integer literal in base 8. 000451 in base 8 is 297 in base 10, and 000451.01 is parsed as int(297) dot int(1) instead of a single number literal.
Remove the initial zeros and it should work.
Numbers starting with a zero are interpreted as octal numbers. But octal numbers are only integers and not floating point numbers. So try this:
eval("451.01")
But it would be better if you use the parseFloat function:
parseFloat("000451.01")
Related
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.
I receive a long XML from backend. To further use the xml I convert it to JSON object using one of the standard XMLtoJSON javascript library. The issue is, some of the XML value contains number with leading zeros eg: 001072.
The problem is, when javascript library converts xml to JSON, number with leading zeros give completely different value.
For example
“001072” converts “570”
Other times it parse it correctly. For example:
“0045678” converts to 45678
The problem is how javascript handle number with zeros. I don’t know the reason of this strange behavior!!
Please suggest a solution which can parse number with zeros consistently and how can I use it with xmltojson library
This is most likely a problem with octal literals. If a number starts with a leading 0, JavaScript by default will try to parse it as an octal literal.
For this reason, you should always specify the radix parameter when calling parseInt. The library probably does not do that.
parseInt("012", 8); // 10
parseInt("012", 10); // 12
I think this is the offending line in the library, probably. Either edit the library, or edit your XML.
Octal numbers with the leading zero are on the way out. For ECMAScript5 they can still cause problems and are thus not allowed in strict mode and throw a runtime error. You really should not be using 3rd party scripts that are not in strict mode they are dangerous for way too many reasons, as you can see with the handling of the octal numbers.
As ECMAScript 6 becomes more wide spread the use of the leading zero will be pushed out all together.
Octals literals will have a '0o' prefix 0o10 === 8 can be uppercase 'o' but I am sure you can see this will be a hassle. ES6 will also formalise the binary format with the prefix 0b1000 === 8 though most browsers have supported it for some time. Hex has also been around for a while 0x08 == 8
The reason some numbers with leading zeros are decmil and some octal is dependent on what digits are in the number. Octal does not use the digits 8 and 9 so any number that have these digits can not be octal.
I have just observed that the parseInt function doesn't take care about the decimals in case of integers (numbers containing the e character).
Let's take an example: -3.67394039744206e-15
> parseInt(-3.67394039744206e-15)
-3
> -3.67394039744206e-15.toFixed(19)
-3.6739e-15
> -3.67394039744206e-15.toFixed(2)
-0
> Math.round(-3.67394039744206e-15)
0
I expected that the parseInt will also return 0. What's going on at lower level? Why does parseInt return 3 in this case (some snippets from the source code would be appreciated)?
In this example I'm using node v0.12.1, but I expect same to happen in browser and other JavaScript engines.
I think the reason is parseInt converts the passed value to string by calling ToString which will return "-3.67394039744206e-15", then parses it so it will consider -3 and will return it.
The mdn documentation
The parseInt function converts its first argument to a string, parses
it, and returns an integer or NaN
parseInt(-3.67394039744206e-15) === -3
The parseInt function expects a string as the first argument. JavaScript will call toString method behind the scene if the argument is not a string. So the expression is evaluated as follows:
(-3.67394039744206e-15).toString()
// "-3.67394039744206e-15"
parseInt("-3.67394039744206e-15")
// -3
-3.67394039744206e-15.toFixed(19) === -3.6739e-15
This expression is parsed as:
Unary - operator
The number literal 3.67394039744206e-15
.toFixed() -- property accessor, property name and function invocation
The way number literals are parsed is described here. Interestingly, +/- are not part of the number literal. So we have:
// property accessor has higher precedence than unary - operator
3.67394039744206e-15.toFixed(19)
// "0.0000000000000036739"
-"0.0000000000000036739"
// -3.6739e-15
Likewise for -3.67394039744206e-15.toFixed(2):
3.67394039744206e-15.toFixed(2)
// "0.00"
-"0.00"
// -0
If the parsed string (stripped of +/- sign) contains any character that is not a radix digit (10 in your case), then a substring is created containing all the other characters before such character discarding those unrecognized characters.
In the case of -3.67394039744206e-15, the conversion starts and the radix is determined as base 10 -> The conversion happens till it encounters '.' which is not a valid character in base 10 - Thus, effectively, the conversion happens for 3 which gives the value 3 and then the sign is applied, thus -3.
For implementation logic - http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.2
More Examples -
alert(parseInt("2711e2", 16));
alert(parseInt("2711e2", 10));
TO note:
The radix starts out at base 10.
If the first character is a '0', it switches to base 8.
If the next character is an 'x', it switches to base 16.
It tries to parse strings to integers. My suspicion is that your floats are first getting casted to strings. Then rather than parsing the whole value then rounding, it uses a character by character parsing function and will stop when it gets to the first decimal point ignoring any decimal places or exponents.
Some examples here http://www.w3schools.com/jsref/jsref_parseint.asp
parseInt has the purpose of parsing a string and not a number:
The parseInt() function parses a string argument and returns an
integer of the specified radix (the base in mathematical numeral
systems).
And parseInt calls the function ToString wherein all the non numerical characters are ignored.
You can use Math.round, which also parses strings, and rounds a number to the nearest integer:
Math.round("12.2e-2") === 0 //true
Math.round("12.2e-2") may round up or down based on the value. Hence may cause issues.
new Number("3.2343e-10").toFixed(0) may solve the issue.
Looks like you try to calculate using parseFloat, this will give you the correct answer.
parseInt as it says, returns an integer, whereas parseFloat returns a floating-point number or exponential number:
parseInt(-3.67394039744206e-15) = -3
parseFloat(-3.67394039744206e-15) = -3.67394039744206e-15
console.log('parseInt(-3.67394039744206e-15) = ' , parseInt(-3.67394039744206e-15));
console.log('parseFloat(-3.67394039744206e-15) = ',parseFloat(-3.67394039744206e-15));
My problem is really simple but I'm not sure if there's a "native" solution using JSON.parse.
I receive this string from an API :
{ "key" : -922271061845347495 }
When I'm using JSON.parse on this string, it turns into this object:
{ "key" : -922271061845347500 }
As you can see, the parsing stops when the number is too long (you can check this behavior here). It has only 15 exact digits, the last one is rounded and those after are set to 0. Is there a "native" solution to keep the exact value ? (it's an ID so I can't round it)
I know I can use regex to solve this problem but I'd prefer to use a "native" method if it exists.
Your assumption that the parsing stops after certain digits is incorrect.
It says here:
In JavaScript all numbers are floating-point numbers. JavaScript uses
the standard 8 byte IEEE floating-point numeric format, which means
the range is from:
±1.7976931348623157 x 10308 - very large, and ±5 x 10-324 - very small.
As JavaScript uses floating-point numbers the accuracy is only assured
for integers between: -9007199254740992 (-253) and 9007199254740992
(253)
You number lies outside the "accurate" range hence it is converted to the nearest representation of the JavaScript number. Any attempt to evaluate this number (using JSON.parse, eval, parseInt) will cause data loss. I therefore recommend that you pass the key as a string. If you do not control the API, file a feature request.
The number is too big to be parsed correctly.
One solution is:
Preprocessing your string from API to convert it into string before parsing.
Preform normal parsing
Optionally, you could convert it back into number for your own purpose.
Here is the RegExp to convert all numbers in your string (proceeded with :) into strings:
// convert all number fields into strings to maintain precision
// : 922271061845347495, => : "922271061845347495",
stringFromApi = stringFromApi.replace(/:\s*(-?\d+),/g, ': "$1",');
Regex explanation:
\s* any number of spaces
-? one or zero '-' symbols (negative number support)
\d+ one or more digits
(...) will be put in the $1 variable
I'm passing as parameter an id to a javascript function, because it comes from UI, it's left zero padded. but it seems to have (maybe) "strange" behaviour?
console.log(0000020948); //20948
console.log(0000022115); //9293 which is 22115's octal
console.log(parseInt(0000022115, 10)); // 9293 which is 22115's octal
console.log(0000033959); //33959
console.log(20948); //20948
console.log(22115); //22115
console.log(33959); //33959
how can I make sure they are parsing to right numebr they are? (decimal)
EDIT:
just make it clearer:
those numbers come from the server and are zero padded strings. and I'm making a delete button for each one.
like:
function printDelButton(value){
console.log(typeof value); //output string
return '<img src="images/del.png">'
}
and
function printDelButton(value){
console.log(typeof value); //output numeric
console.log(value); //here output as octal .... :S
}
I tried :
console.log(parseInt(0000022115, 10)); // 9293 which is 22115's octal
and still parsing as Octal
If you receive your parameters as string objects, it should work to use
parseInt(string, 10)
to interpret strings as decimal, even if they are beginning with 0.
In your test, you pass the parseInt method a number, not a string, maybe that's why it doesn't return the expected result.
Try
parseInt('0000022115', 10)
instead of
parseInt(0000022115, 10)
that does return 221115 for me.
If you start it with a 0, it's interpreted as an Octal number.
See http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference#quickIDX2
Note the article's warning here:
You should never precede a number with a zero unless you are
specifically looking for an octal conversion!
Consider looking here for ideas on removing the leadings 0s:
Truncate leading zeros of a string in Javascript
Leading 0s indicate that the number is octal.
parseInt parses a string containing a number.
parseInt(0000022115, 10) passes a numeric literal. The literal is parsed in octal by the JS interpreter, so you're passing a raw numeric value to parseInt.
Unless you can intercept a string version of this number, you're out of luck.
That being said, if you can get a string version of your octal (calling toString() won't help), this will work:
parseInt(variable_string.replace(/^0+/, ''), 10);
Try
/^[0]*([1-9]\d)/.exec(numberFromUI)[0]
That should give you just the numbers stripping the zeros (if you have to support decimals, you'll need to edit to account for the '.', and of course ',' is fun too... and I really hope you don't have to handle all the crazy different ways Europeans write numbers! )
If number came from server as zero padded string then use +"0000022115"
console.log(+"0000022115")
if (021 < 019) console.log('Paradox');
JS treat zero padded numbers like octal only if they are valid octal - if not then it treat it as decimal. To not allow paradox 'use strict' mode
'use strict'
if (021 < 019) console.log('Paradox');