# javascript - 将距离字符串转换为数字

#### 4 个答案:

``````var dist = '1,525 KM';
dist = Number(dist.replace(/[^\d]/g, ''));
``````

``````valueInKm = value * 0.001
``````

``````function getDistance( dist ){
var match = /^([ -]?[1-9]\d{0,2}(?:(?:([,.])(?:\d{3})*\d{3}(?:(?!)[,.]\d )?)|[,.]\d )?|[ -]?0(?:[,.]\d )?) (. )\$/
.exec( dist );
if ( match ){
return {
value: parseFloat( match[1].split( match[2] ).join( '' ).replace( ',', '.' ), 10 ),
units: match[3]
};
}
return { value: null, units: null };
}
``````

<强>测试

``````var results = [
{ in: "0 m", dist: 0, units: "m" },
{ in: "10 m", dist: 10, units: "m" },
{ in: "0.2 m", dist: 0.2, units: "m" },
{ in: "0,2 m", dist: 0.2, units: "m" },
{ in: "1,202 m", dist: 1202, units: "m" },
{ in: "1,524.2 KM", dist: 1524.2, units: "KM" },
{ in: "1.524,2 KM", dist: 1524.2, units: "KM" },
{ in: "9,234,524.2 KM", dist: 9234524.2, units: "KM" },
{ in: "9.234.524,2 KM", dist: 9234524.2, units: "KM" },
];

var successes = 0;
for ( var i = 0; i < results.length; i   ){
var v = getDistance( results[i].in );
if ( v.value == results[i].dist && v.units == results[i].units )
successes
else
console.log( results[i].in, v.value, v.units );
}
console.log( "Successes:", successes, "Failures:", results.length - successes );
``````

``````var text = "1,525 KM";

var n = parseInt(text.replace(/[^\d ]/g, ""));

console.log(n);``````

0条回复