草庐IT

java - 在不修改小数的情况下将逗号(分组分隔符)添加到数字?

coder 2023-09-03 原文

我正在尝试格式化字符串以在 3 位数字组之间添加逗号

如:

1200.20 >> 1,200.20
15000   >> 15,000

我正在尝试弄清楚如何使用 DecimalFormat 来实现这一点,到目前为止,我一直在使用我自己的脚本,该脚本似乎过于复杂。我不知道该怎么做,使用 # 只是隐藏尾随零并使用 0 将它们添加到数字中。

这就是我现在正在尝试的:

DecimalFormat df = new DecimalFormat("###,###.####", new DecimalFormatSymbols(Locale.US));
resultStr = df.format(Double.valueOf(resultStr));

我确信这一定很容易,但我不确定如何去做。我不必使用 DecimalFormat 来做,我只是认为这是更简单的方法。我怎样才能简单地添加逗号而不以任何方式修改小数点?

最佳答案

您应该使用 NumberFormat 对象并将其设置为使用分组。有点像

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class NumberFormatEg {
   public static void main(String[] args) {
      NumberFormat myFormat = NumberFormat.getInstance();
      myFormat.setGroupingUsed(true);

      double[] numbers = { 11220.00, 232323232.24, 121211.55, 102.121212 };

      for (double d : numbers) {
         System.out.println(myFormat.format(d));
      }
      System.out.println();

      DecimalFormat decimalFormat = new DecimalFormat("#.00");
      decimalFormat.setGroupingUsed(true);
      decimalFormat.setGroupingSize(3);

      for (double d : numbers) {
         System.out.println(decimalFormat.format(d));
      }

      System.out.println("\nFor Germany");

      NumberFormat anotherFormat = NumberFormat
            .getNumberInstance(Locale.GERMAN);
      if (anotherFormat instanceof DecimalFormat) {
         DecimalFormat anotherDFormat = (DecimalFormat) anotherFormat;
         anotherDFormat.applyPattern("#.00");
         anotherDFormat.setGroupingUsed(true);
         anotherDFormat.setGroupingSize(3);

         for (double d : numbers) {
            System.out.println(anotherDFormat.format(d));
         }

      }

      System.out.println("\nFor US:");

      anotherFormat = NumberFormat.getNumberInstance(Locale.US);
      if (anotherFormat instanceof DecimalFormat) {
         DecimalFormat anotherDFormat = (DecimalFormat) anotherFormat;
         anotherDFormat.applyPattern("#.00");
         anotherDFormat.setGroupingUsed(true);
         anotherDFormat.setGroupingSize(3);

         for (double d : numbers) {
            System.out.println(anotherDFormat.format(d));
         }

      }
   }
}

返回:

11,220
232,323,232.24
121,211.55
102.121

11,220.00
232,323,232.24
121,211.55
102.12

For Germany
11.220,00
232.323.232,24
121.211,55
102,12

For US:
11,220.00
232,323,232.24
121,211.55
102.12

这样做的一个优点是解决方案可以是特定于区域设置的。

已编辑
现在显示一个带有 DecimalFormat 对象的示例。请注意,如果您使用它,您应该设置分组大小。

关于java - 在不修改小数的情况下将逗号(分组分隔符)添加到数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15328647/

有关java - 在不修改小数的情况下将逗号(分组分隔符)添加到数字?的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  3. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  4. ruby - 默认情况下使选项为 false - 2

    这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb

  5. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  6. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  7. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  8. ruby - 可以通过多少种方法将方法添加到 ruby​​ 对象? - 2

    当谈到运行时自省(introspection)和动态代码生成时,我认为ruby​​没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby​​的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资

  9. ruby - 在不使用 RVM 的情况下在 Mac 上卸载和升级 Ruby - 2

    我最近决定从我的系统中卸载RVM。在thispage提出的一些论点说服我:实际上,我的决定是,我根本不想担心Ruby的多个版本。我只想使用1.9.2-p290版本而不用担心其他任何事情。但是,当我在我的Mac上运行ruby--version时,它告诉我我的版本是1.8.7。我四处寻找如何简单地从我的Mac上卸载这个Ruby,但奇怪的是我没有找到任何东西。似乎唯一想卸载Ruby的人运行linux,而使用Mac的每个人都推荐RVM。如何从我的Mac上卸载Ruby1.8.7?我想升级到1.9.2-p290版本,并且我希望我的系统上只有一个版本。 最佳答案

  10. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

随机推荐