简体   繁体   中英

Double with custom quantity zero's after dot

I have two Integer values and I need create Double value from combining this two values in following way:

A.CB

where:

A — first integer value B — second integer value C — zero's to match total length

Basically, CB is always have to be 9 digits in total, that's mean when B = 1 I need that C will be 8 zero's, if B=100 I need C will be 6 zero's. To get this results: 15.000000001 and 17.000000100

What is the best way to approach this logic in code? I mean I can write custom method to create this logic, but is Java already have something for this case to just use it, without creating custom methods? Better if it's possible without using string format functions (to not convert Integer values to String).

Something like this?

    int A = 123, B = 450;
    System.out.println(String.format("%.09f", A + 1e-9 * B));

Will print

123.000000450

PS String.format is required because of your trailing-zeros-after-the-comma requirement. Those zeros don't actually exist, so you need some way to pad your output, and String.format is a convenient way to do that. If you just want a double value, you don't need String.format .

Divide b / 1000000000.0 :

int a = 12;
int b = 123;
double x = a + b / 1000000000.0;
System.out.println(x);

Will print:

12.000000123

Unless b 's length is longer than 9 digits, you will get what you want.

int a = 12;
int b = 123;

// How many digits in b?
int blen = (int)Math.log10(b);

// Make a string of zeros
String padding = "00000000".substring(blen);

System.out.println(a + "." + padding + b);

This will fail apart if b is very large, as blen will be larger than the padding, and so substring will fail. Also, negative b will mess things up.

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