如何找到出现语法错误的原因以及如何实现全球化格式

how to find why the syntax error occur & how to achieve a globalize format

这是我的代码,

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(.635676576567, 'n2') = .64
Globalize.format(#50.635676576567, 'n2') = #50.64
Globalize.format(50.635676576567world, 'n2') = 50.64 world

如何实现?

您可以在应用 Globalize.format

后简单地添加必要的符号
Globalize.format(50.635676576567, 'n2')+'%';
Globalize.format(50.635676576567, 'n2')+'C';
'#'+Globalize.format(50.635676576567, 'n2');

以此类推

您只需在输出中添加符号,即:

Globalize.format(50.635676576567, 'n2') + '%' = "50.64%"
Globalize.format(50.635676576567, 'n2') + 'C' = "50.64C"
Globalize.format(50.635676576567, 'n2') + '@' = "50.64@"
'$' + Globalize.format(50.635676576567, 'n2') = ".64"
'#' + Globalize.format(50.635676576567, 'n2') = "#50.64"
Globalize.format(50.635676576567, 'n2') + ' world' = "50.64 world"

请尝试此代码。您必须拆分字符和数字才能执行全球化格式

var str = "Globalize.format(50.635676576567world, 'n2') Globalize.format(.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);

希望对您有所帮助。