Home > OS >  Formatting variable of type double when declaring it
Formatting variable of type double when declaring it

Time:04-02

I'm aware of the many ways of formatting a double variable to X # of decimal places. With that being said:

static double currentSelectedPrice = 0.00; //format to 2 decimal places
static double usercashBalance = 0.00

The code below is found at different locations through my code. I do not want to go through the code and format the result of (currentSelectedPrice - usercashBalance)

if(usercashBalance < currentSelectedPrice)                
{
      System.out.println("Remaing: $"   (currentSelectedPrice - usercashBalance));
      continue;
}

It would be ideal to already have those variables formatted when declaring them (so the output of its operations is also formatted). Is that possible?

CodePudding user response:

A double (or Double) has no formatting information!

It is just a floating point representation of a value.

These two lines result in identical values for d:

double d = 1;
double d = 1.00000000;

You can however control how a double is rendered/formatted, eg

String formatted = String.format("%,.4f", d);

Renders the double value with 4 decimal places.


Tip: if you store all currency values as an int of cents, and render it as decimal dollars, most of your problems disappear.

CodePudding user response:

I would try something like this

if(usercashBalance < currentSelectedPrice)                
{
    System.out.printf("Remaing: $%.<x>f", (currentSelectedPrice - usercashBalance));
    continue;
}

x indicating the number of decimals you want to print from your result

  • Related