Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add decimal point before x digits in Java

Tags:

java

formatter

Lets suppose I have a value 12345678 and a number say x=2, and I want the final output as 123456.78 and if the value of x is 4, the final output would be 1234.5678.

Please tell how would I can achieve this?

like image 378
Jaffy Avatar asked Nov 29 '22 13:11

Jaffy


2 Answers

BigInteger d = new BigInteger("12345");
BigDecimal one = new BigDecimal(d, 3);//12.345
BigDecimal two = new BigDecimal(d, 2);//123.45
like image 30
rajesh Avatar answered Dec 04 '22 15:12

rajesh


Given that you're dealing with shifting a decimal point, I'd probably use BigDecimal:

long integral = 12345678L;
int x = 4; // Or 2, or whatever
BigDecimal unscaled = new BigDecimal(integral);
BigDecimal scaled = unscaled.scaleByPowerOfTen(-x);
System.out.println(scaled); // 1234.5678
like image 139
Jon Skeet Avatar answered Dec 04 '22 16:12

Jon Skeet