简体   繁体   English

如何在Javascript中将一个字符串拆分为两个浮点数?

[英]How can I split a string into two float numbers in Javascript?

function xyDistance(from,to){
var s=from.split(",");
var x1=parseFloat(s[0]);
 var y1=parseFloat(s[1]);


 var dt = Math.sqrt( (x2-x1)**2+(y2-y1)**2);
 return dt;
}

I will enter the two coordinates as a string.我将输入两个坐标作为字符串。 I have split them, but I don't know how to separate the X and Y coordinates of two points.The photo shows the input value and expected output value.我已经把它们分开了,但我不知道如何分开两点的 X 和 Y 坐标。照片显示了输入值和预期的 output 值。 在此处输入图像描述

For each from , to , you just have to split it and parseInt对于每个fromto ,您只需将其拆分并 parseInt

 function xyDistance(from, to) { var [x1, y1] = from.split(",").map(axis => parseInt(axis, 10)); var [x2, y2] = to.split(",").map(axis => parseInt(axis, 10)); var dt = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2); return dt; } console.log(xyDistance('1,1', '0,0'))

I'm not sure what your algorithm is supposed to be doing, but to get the x,y coords of both, just do a split on each argument.我不确定您的算法应该做什么,但是要获得两者的 x,y 坐标,只需对每个参数进行拆分。 And, fyi, all numbers in JavaScript are floating point (whole numbers just aren't displayed with decimals unless you format them to).而且,仅供参考,JavaScript 中的所有数字都是浮点数(除非将它们格式化为整数,否则不会以小数显示)。

 function xyDistance(from,to){ var f = from.split(","); var x1 = parseFloat(f[0]); var y1 = parseFloat(f[1]); var t = to.split(","); var x2 = parseFloat(t[0]); var y2 = parseFloat(t[1]); console.log("from x,y are: " + x1 + ", " + y1); console.log("to x,y are: " + x2 + ", " + y2); } xyDistance("1,1","0,0"); xyDistance("1,1","-1,-1");

 function xyDistance(from,to){ const [x1, y1] = from.split(","); const [x2, y2] = to.split(","); const dt = Math.sqrt((x2-x1)**2+(y2-y1)**2); return dt; } console.log(xyDistance("2,1", "0,1"))

try above code, no need to parse float试试上面的代码,不需要解析浮点数

You could split the values and take the delta of same index as value for Math.hypot .您可以拆分值并将相同索引的增量作为Math.hypot的值。

 function xyDistance(from, to) { const f = from.split(','); t = to.split(','); return Math.hypot(f[0] - t[0], f[1] - t[1]); } console.log(xyDistance("1,1", "0,0")); console.log(xyDistance("1,1", "-1,-1"));

This code will work此代码将起作用

function xyDistance(from,to){
var f=from.split(",");
var fx=parseFloat(f[0]);
var fy=parseFloat(f[1]);

var t=to.split(",");
var tx=parseFloat(t[0]);
var ty=parseFloat(t[1]);


 var dt = Math.sqrt( (fx-tx)**2+(fy-ty)**2);
 return dt;
}

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

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