简体   繁体   中英

Formatting variable of type double when declaring it

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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