这是我的代码,
Globalize.format(50.635676576567%, 'n2')
它抛出语法错误,因为 % 已添加到数字中。但我需要将输出显示为 50.64%。如何实现通用方式{注意:符号可以是任何字符或特殊数字......}
示例:
Globalize.format(50.635676576567%, 'n2') = 50.64%
Globalize.format(50.635676576567C, 'n2') = 50.64C
Globalize.format(50.635676576567@, 'n2') = 50.64@
Globalize.format($50.635676576567, 'n2') = $50.64
Globalize.format(#50.635676576567, 'n2') = #50.64
Globalize.format(50.635676576567world, 'n2') = 50.64 world
如何实现?
最佳答案
请尝试此代码。您必须拆分字符和数字才能执行全局化格式
var str = "Globalize.format(50.635676576567world, 'n2') Globalize.format($50.635676576567, 'n2') ",
substr;
while (str.indexOf('Globalize.format(') >= 0) {
substr = str.substring(str.indexOf('Globalize.format('), str.indexOf(")") + 1);
var calculate = substr.substring(substr.indexOf('(') + 1, substr.indexOf(",")),
character = calculate.replace(/[0-9.]/g, ''),
numberic = calculate.replace(/[^\d.]/g, ''),
index = calculate.indexOf(character),
formatedString = substr.replace(character, "");
if (index == 0)
formatedString = character + eval(formatedString);
else
formatedString = eval(formatedString) + character;
str = str.replace(substr, formatedString);
}
console.log(str);
希望这对您有帮助。
关于javascript - 如何查找发生语法错误的原因以及如何实现全局化格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33908999/