How to print a decimal number with a dot, not a comma?

Asked

Viewed 1,829 times

4

If I do:

float a=5;
System.out.printf("%d", a);

His exit will be:

5.000000

How do I print 5.000000? I mean, I want to replace the comma with the dot.

  • 6

    Do you want this for the entire application or just for this data? If you want to change in general for all applications, it’s OS configuration. If you want to change your entire application, it may be the case to set the locale. If you want to change only in some specific cases, and leave the rest of your application numbers comma, it is already the case to work separately on the items. It would be legal [Dit] the question and clarify.

  • then the OS language defines whether it will be a semicolon? if I send . jar to a PC with OS in English it will print with dot? where appropriate, it is inevitable?

  • have cases and cases. The best friend to know what happens in your specific case is the test. I’ve touched three possibilities, but you have more to consider. I made the speculations based on what you can imagine by the question, only testing in the real situation to better measure.

  • I think that’s enough for me

2 answers

7

Maybe this will help you:

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

public class Teste {
    public static NumberFormat seuFormato() {
        DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ROOT);
        symbols.setDecimalSeparator(',');
        symbols.setGroupingSeparator('.');
        return new DecimalFormat("#0.00", symbols);
    }

    public static void main(String[] args) {
        NumberFormat formatter = seuFormato();
        float a = 5;
        System.out.println(formatter.format(a));
    }
}

See here working on Ideone.

Obtained on the basis of an example of the Oracle website.

-1

I believe that using replace() solves your problem an example below:

import java.io.*;

public class Test{
   public static void main(String args[]){
      String Str = new String("Welcome to Tutorialspoint.com");

      System.out.print("Return Value :" );
      System.out.println(Str.replace('o', 'T'));

      System.out.print("Return Value :" );
      System.out.println(Str.replace('l', 'D'));
   }

Upshot:

WelcTme tT TutTrialspTint.cTm
WeDcome to TutoriaDspoint.com
  • 1

    Replace nay is recommended to convert numbers, because the number formatting depends on the location in which the JVM is configured, sometimes returning commas or points, and numbers with thousands separators such as 1.234,45 will also give incorrect results.

  • Thanks for the feedback, really forgot that possibility makes perfect sense :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.