简体   繁体   English

从String到float的奇怪转换

[英]Weird conversion from String to float

I have a webview with javascript-interface. 我有一个带有javascript界面​​的webview。

From within this webview i do certain javascript operations. 在此Webview中,我执行某些javascript操作。

In one of those i set an onclick attribute for one of the elements in my webcontent. 在其中之一中,我为Webcontent中的元素之一设置了onclick属性。 ( using jquery) (使用jQuery)

button.attr("onclick", "Android.doStuff(".concat(stringContainingOnlyNumbers).concat(")"));

As you might guess the variable stringContainingOnlyNumbers holds a String containing only numbers. 您可能会猜到,变量stringContainingOnlyNumbers包含仅包含数字的String。

Android is the keyword for my javascript-interface. Android是我的javascript-interface的关键字。

If i click the button i manipulated the method doStuff is gettin called on the interface. 如果单击该按钮,则将操作doStuff方法在界面上调用。

Everything fine so far. 到目前为止一切都很好。

But what the String Parameter holding looks like a float value. 但是,字符串参数保留的内容看起来像一个浮点值。

So what looks like this on js side: 因此,在JS端看起来像这样:

1344810353

Comes out on my interface like this: 像这样在我的界面上显示出来:

1.34447e+09

Can anyone help me out here and explain why this conversion happens? 谁能在这里帮助我,解释为什么会发生这种转换?

That isn't really a conversion, it's just rewriting it to fewer decimal digits using scientific notation. 那实际上不是转换,只是使用科学计数法将其重写为更少的十进制数字。
1344810353 rounded to 6 digits is 1.34447e+09, which btw is 1.34447 * 10^9. 1344810353舍入为6位数是1.34447e + 09,顺便说一句是1.34447 * 10 ^ 9。

It's a float, and javascript tends to shorten numbers when concatenating them as strings. 这是一个浮点数,当将它们串联为字符串时,javascript倾向于缩短数字。
Here's an example: http://jsfiddle.net/YGC8B/ 这是一个示例: http : //jsfiddle.net/YGC8B/

You can fix this by iterating through the numbers digits and displaying them one by one. 您可以通过遍历数字位并逐一显示它们来解决此问题。

function getString(number) {
    var numstring = "";
    var num = number;
    while (num > 0) {
        numstring = num % 10 + numstring;
        num -= num % 10;
        num /= 10;
    }
    return numstring;
}
var number = 1344810353;
log(getString(number)); // or however your output it

Here's a working example: http://jsfiddle.net/Tj5Zy/ 这是一个工作示例: http : //jsfiddle.net/Tj5Zy/


A side note: 旁注:

It's best not to use the onclick attribute of an element, it's slightly deprecated. 最好不要使用元素的onclick属性,因为它已经过时了。 I would recommend attaching the event. 我建议附加活动。
And since you're using jQuery, it's just all the easier. 而且由于您使用的是jQuery,因此非常容易。

button.bind('click',function() {
    Android.doStuff(stringContainingOnlyNumbers);
});

What is happening there is not a conversion to float, but you are getting a scientific notation for that integer. 发生的事情没有转换为浮点数,但是您对该整数有了科学的表示法。 It must be happening in concat. 它一定是在concat中发生的。 Can't you do something like: 你不能做这样的事情:

button.attr("onclick", "Android.doStuff(" + stringContainingOnlyNumbers + ")");

?

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

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