简体   繁体   English

parseFloat 不适用于移动设备

[英]parseFloat does not work on mobile devices

I am writing a very basic html calculator.我正在编写一个非常基本的 html 计算器。 The end result and user inputs are shown in "textDisplay_" area below:最终结果和用户输入显示在下面的“textDisplay_”区域中:

<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:我还有一个 JavaScript 代码,它使用以下函数获取并解析显示的值到浮点数:

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.这段代码在桌面浏览器上运行得很好(我已经在 Chrome、FireFox 和 IE 上测试过)它们看起来都不错,让我们说如果我输入:3.14*2 并按“=”他们给我 6.28。

However on my android 4, using the latest versions of mobile chrome and firefox all the decimal numbers get rounded down!但是,在我的 android 4 上,使用最新版本的移动 chrome 和 firefox,所有十进制数字都会四舍五入! so If I punch in "3.14*2=", I will get "6"!所以如果我输入“3.14*2=”,我会得到“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.我查看了其他包含 parseFloat 的帖子不起作用,但没有一个与此问题类似。 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.一种选择是编写我自己的 parseFloat(我以前为微控制器做过这个!)但我真的不想那样做。

Thanks a lot in advance.非常感谢。

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/ 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: str是一个包含浮点数的字符串,下面所有的都产生相同的、正确的浮点值:

var values = [ str*1, 1*str, 1.0*str, parseFloat(str) ];

You can try:你可以试试:

var t = 1.0 * getCurrentText();

to get a float.得到一个浮动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM