Why am I getting weird result using parseInt in node.js? (different result from chrome js console)
Undefined behavior occurs when the string being passed to parseInt has a leading 0, and you leave off the radix parameter.
An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
Some browsers default to base 8, and some to base 10. I'm not sure what the docs say about Node, but clearly it's assuming base 8, since 3010123
in base 8 is 790611
in base 10.
You'll want to use:
parseInt("03010123", 10);
Problems with pasrseInt()
The main problem here is the code that reads x
and y
runs before any valuie is in them.
The second problem is when you blur
the control with id outlet_actual_1
you call your method, but with no arguments, when it expects actual
and design
to be passed in as arguments.
Finally if using valueAsNumber
there's no need to use parseInt
. If you do want to use it then read the value
and make sure you use the radix like parseInt(document.getElementById("outlet_actual_1" ).value, 10)
The simple way to get this going is to move the code that reads x
and y
inside the method and remove the arguments, but there's probably more to it than that, I suspect you want to recalculate any time either field changes so lets add that too:
function outletIndex() {
const actual = document.getElementById("outlet_actual_1" ).valueAsNumber || 0 ;
const design = document.getElementById("outlet_design_1").valueAsNumber || 0 ;
let result1 = actual / design * 100;
var indexArray = [];
indexArray.push(result1);
console.log(indexArray, result1);
if (!isNaN(result1)) {
document.getElementById("percentage").textContent = `${result1.toFixed(1)}%`;
}
}
<table>
<tr>
<div class="form-group row 1" id="outlets1">
<td><label
>Outlet Design</label>
<input
name = "outlet 1 design"
class="form-control design_1"
id="outlet_design_1"
type="number"
placeholder="Outlet 1 Design"
onblur="outletIndex();"
/>
</td>
<td><label
>Outlet Actual</label>
<input
name="outlet 1 actual"
class="form-control actual_1"
id="outlet_actual_1"
type="number"
placeholder="Outlet 1 Actual"
onblur="outletIndex();"
/>
</td>
<td><label
>Outlet Balance</label>
<input
name="outlet_balance"
class="form-control"
input value=""
id="outlet_balance_1"
type="text"
placeholder="Outlet 1 Balance"
/>
</td><td>
<div class="proportion" id="percentage">
</div>
</td>
</div>
</tr>
Why does JavaScript's parseInt(0.0000005) print 5?
Based on ecmascript standard:
The
parseInt
function produces an integralNumber
dictated by interpretation of the contents of thestring
argument according to the specified radix.
Part1 - Converting 0.0000005
to string
:
The first step of parseInt function is converting the input to string if it is not:
19.2.5 parseInt ( string, radix )
When the parseInt function is called, the following steps are taken:
Let inputString be ? ToString(string).
- Let S be ! TrimString(inputString, start).
...
In each case, the string output is as follows:
String(0.5); // => '0.5'
String(0.05); // => '0.05'
String(0.005); // => '0.005'
String(0.0005); // => '0.0005'
String(0.00005); // => '0.00005'
String(0.000005); // => '0.000005'
String(0.0000005); // => '5e-7'
Part2 - Converting 5e-7
to integer
:
So, it means when we use parseInt(0.0000005)
, it is equal to parseInt('5e-7')
and based on the definition:
parseInt may interpret only a leading portion of string as an integer value; it ignores any code units that cannot be interpreted as part of the notation of an integer, and no indication is given that any such code units were ignored.
So the answer will return 5
only because it is the only character which is a number till a noncharacter e
, so the rest of it e-7
will be discarded.
Thanks to @jcalz, I should mention that:
Don't use
parseInt(x)
forx
that isn’t astring
. If you already have anumber
presumably you wantMath.round()
orMath.floor()
or something.
Why does Date.parse give incorrect results?
Until the 5th edition spec came out, the Date.parse
method was completely implementation dependent (new Date(string)
is equivalent to Date.parse(string)
except the latter returns a number rather than a Date
). In the 5th edition spec the requirement was added to support a simplified (and slightly incorrect) ISO-8601 (also see What are valid Date Time Strings in JavaScript?). But other than that, there was no requirement for what Date.parse
/ new Date(string)
should accept other than that they had to accept whatever Date#toString
output (without saying what that was).
As of ECMAScript 2017 (edition 8), implementations were required to parse their output for Date#toString
and Date#toUTCString
, but the format of those strings was not specified.
As of ECMAScript 2019 (edition 9) the format for Date#toString
and Date#toUTCString
, have been specified as (respectively):
- ddd MMM DD YYYY HH:mm:ss ZZ [(timezone name)]
e.g. Tue Jul 10 2018 18:39:58 GMT+0530 (IST) - ddd, DD MMM YYYY HH:mm:ss Z
e.g. Tue 10 Jul 2018 13:09:58 GMT
providing 2 more formats that Date.parse
should parse reliably in new implementations (noting that support is not ubiquitous and non–compliant implementations will remain in use for some time).
I would recommend that date strings are parsed manually and the Date constructor used with year, month and day arguments to avoid ambiguity:
// parse a date in yyyy-mm-dd format
function parseDate(input) {
let parts = input.split('-');
// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // Note: months are 0-based
}
Related Topics
Stop a Youtube Video with Jquery
Rails 4 - Gmaps4Rails - Map Won't Render
Get Column from a Two Dimensional Array
Do I Need to Return After Early Resolve/Reject
What's the Best Way to Calculate Date Difference in JavaScript
Headless Browser for Python (JavaScript Support Required!)
How to Get an Ajax Get-Request to Wait for the Page to Be Rendered Before Returning a Response
How to Format a Utc Date as a 'Yyyy-Mm-Dd Hh:Mm:Ss' String Using Nodejs
How to Enable Touch on Multiple Buttons Simultaneously in React Native
Combined Comparison/"Spaceship" Operator (<=>) in JavaScript
Extending an Object in JavaScript
JavaScript Module Pattern with Example
JavaScript for "Add to Home Screen" on Iphone
How to Check If a Custom Protocol Supported
What Is Right Way to Do API Call in React Js