2

Is there a way to localize a number and unit like 1,234.56GB using a locale-specific formatter?

There are languages in which there should be a space between the number and the unit, such as Norwegian and Finnish (in addition to the difference in the formatting of the number itself).

Expected Result:

Norwegian - 1 234,56 GB (There should be a space before GB)
English - 1,234.56GB

My code:

        double val = 1234.1744689941406;
        String mb = "MB";

        NumberFormat nf = NumberFormat.getNumberInstance(new Locale("no"));
        DecimalFormat df = (DecimalFormat)nf;
        df.applyPattern("###,###.##");
        df.setPositiveSuffix("MB");
        String output = df.format(val);

But this is giving me a result of 1 234,56GB.

Pseudonymous
  • 625
  • 1
  • 5
  • 13
  • Have looked at [`NumberFormat`](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html)? – MadProgrammer Jan 18 '17 at 08:26
  • Is that gigabytes? Are you following some standard? Do you have a reference? – shmosel Jan 18 '17 at 08:26
  • So you are saying there should be a space *before the positive suffix*? – RealSkeptic Jan 18 '17 at 08:32
  • @RealSkeptic He's saying that there should be a space between `1` and `2` at the start of the text – MadProgrammer Jan 18 '17 at 08:34
  • @MadProgrammer I don't think so, as he specifically shows that his code gives that space as output. – RealSkeptic Jan 18 '17 at 08:35
  • @RealSkeptic Point :P – MadProgrammer Jan 18 '17 at 08:38
  • @RealSkeptic yes there should be a space before positive suffix only for some languages like norwegian and finnish. – Pseudonymous Jan 18 '17 at 08:38
  • 1
    I'm actually not sure if there are also other languages that needs a space before the positive suffix(MB) i am only sure about norwegian and finnish so i really cant use a condition for 2 different format(with space and without a space) so i want to rely on a locale-specific formatter. Since im not that knowledgeable in Java i want to ask if a locale-specific formatter for this type of unit is possible. :) – Pseudonymous Jan 18 '17 at 08:42
  • @Pseudonymous is this possibly relavent http://stackoverflow.com/questions/6670337/need-space-between-currency-symbol-and-amount – Sash Sinha Jan 18 '17 at 08:47
  • I knew I recently read something very similar: http://stackoverflow.com/a/41548046/982149 – Fildor Jan 18 '17 at 09:29
  • Only problem in above answer is: You have to create resource bundles, so the knowledge if there shall be space between value and suffix has to be privided by *you*. – Fildor Jan 18 '17 at 09:35
  • @Fildor i am actually asking for an alternative way aside from using resource bundle. If and only if there really is an alternative way because some might know. Like for date and percentage we have a locale-specific Java formatter that we could use. But how about others like temperature and unit sizes. – Pseudonymous Jan 19 '17 at 02:56

0 Answers0