繁体   English   中英

从java中的字符串值格式化数学表达式中的数字

[英]Formatting numbers in a mathematical expression from String values in java

我知道如何为数字设置千位分隔符,但我需要在String值的数学表达式中显示带有千位分隔符的数字。

基本上,我想要这些结果:

"123456 + 36514"变成"123,456 + 36,514"

"12345678 + 36542 * 69541 / 987654"变为"12,345,678 + 36,542 * 69,541 / 987,654"

和 ...

您想在后跟确切数量的 3 位数块的数字后插入逗号,因此:

(?<=\d)         Positive lookbehind: Match a digit
(?=             Positive lookahead:
   (?:\d{3})+     One or more sequences of 3 digits
   \b             Word-boundary, i.e. end of digit sequence
)

这将匹配您想要逗号的空格,因此请执行replaceAll()

str = str.replaceAll("(?<=\\d)(?=(?:\\d{3})+\\b)", ",");

有关演示,请参阅regex101

我可以为您提供一个算法而不是给出代码:

Loop: String of repression one character at a time
{
  If the current char is 0 to 9 append to tempNumber string
  else
     {
      //by the time you reach this line the number is in the tempNumber string

      Format the number stored in tempNumber // java.text.NumberFormat
      append the formatted number in targetExpression string
      append the current char to the targetExpression string
}

}

暂无
暂无

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

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