简体   繁体   English

如何将字符串转换为数字 javascript

[英]How convert a string into a number javascript

I have a string that is 11.786.775,13 and I need to convert into a number, but if I use parseInt return 11, and if I use parseFloat return 11.786, I need the 11.786.775,13 but as a number.我有一个字符串 11.786.775,13,我需要转换成一个数字,但是如果我使用 parseInt 返回 11,如果我使用 parseFloat 返回 11.786,我需要 11.786.775,13 但作为数字。 Here my code:这是我的代码:

let x = number.toLocaleString('pt-br', {minimumFractionDigits: 2});

replace the dots with an empty string and the comma with a dot and then use parseFloat用空字符串替换点,用点替换逗号,然后使用 parseFloat

const cleanStrNumber = x.replace(/\./g, '').replace(',','.');
const num = parseFloat(cleanStrNumber, 10);

My solution:我的解决方案:

let x = '11.786.775,13';
x = parseFloat(x.split('.').join('').replace(',','.'));
console.log(typeof x, x);

for x equals '11.786.775,13' or '175,13' slower (3%) than .replace(/\./g, '') ;对于 x 等于 '11.786.775,13' 或 '175,13' 比.replace(/\./g, '') but for x = '9.9.9.9.9.9.9.9.9.9.9.9.11.786.775,13', replace is slower than split-join construction但是对于 x = '9.9.9.9.9.9.9.9.9.9.9.9.11.786.775,13',替换比拆分连接构造慢

if you have small numbers(less 4 points), it is better to choose @tomer-almog design(replace).如果您的数字很小(少于 4 分),最好选择 @tomer-almog 设计(替换)。

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

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