问题
I am writing a very basic html calculator. The end result and user inputs are shown in "textDisplay_" area below:
<div id ="textDisplayRow_">
<div id = "textDisplay_" class = "calcTextDisplay">0.0</div>
</div>
I also have a JavaScript code that gets and parses the displayed value into a float using these functions:
function getCurrentText() {
"use strict";
return document.getElementById("textDisplay_").innerHTML;
}
function getDisplayedNum() {
"use strict";
if (getCurrentText() === emptyMesg) {
return maxSafeInt;
}
var t = 1*getCurrentText();
//var t = parseFloat(getCurrentText(), 10);
if ((isNaN(t)) || (t === undefined)) {
return 0;
} else {
return t;
}
}
This code works beautifully on desktop browsers (I have tested it on Chrome, FireFox and IE) They all look good and lets say if I enter: 3.14*2 and press'=' they give me 6.28.
However on my android 4, using the latest versions of mobile chrome and firefox all the decimal numbers get rounded down! so If I punch in "3.14*2=", I will get "6"!
How can I fix this issue? I have looked at other posts containing parseFloat does not work and none of them are similar to this issue. Also both of give similar results:
1*getCurrentText();
parseFloat(getCurrentText(), 10);
One option is to write my own parseFloat (I have previously done this for a micro controller!) but I really dont wanna go that way.
Thanks a lot in advance.
回答1:
You can try:
var t = 1.0 * getCurrentText();
to get a float.
回答2:
I'm pretty sure that your problem is not what you think it is. Please visit this page on your desktop and mobile browser. For me, they produce the same results.
https://jsfiddle.net/xpkhqdLa/1/
With str
being a string holding a floating point number, all of the below produce the same, proper floating-point value:
var values = [ str*1, 1*str, 1.0*str, parseFloat(str) ];
来源:https://stackoverflow.com/questions/36438586/parsefloat-does-not-work-on-mobile-devices