Home > Back-end >  How can I assign value of .2f value of one variable to another variable?
How can I assign value of .2f value of one variable to another variable?

Time:10-31

I want to assign a double value to another variable but only until it's first 2 decimal value. Suppose I have 3.4586748547 value in a variable but I want to save 3.45 in another variable. How can I do this? -I am using JAVA

CodePudding user response:

The fixed point type in Java is BigDecimal.

Floating point is just an approximation, a sum of powers of 2. 3.45 or 3.4499999987 might be the exact same double. But one can round, and when printing with %.2f format will be shown nice. Though the error will be shown when summing or multiplying.

  x = Math.round(x * 100) / 100.0;

Unfortunately.

CodePudding user response:

Using BigDecimal (import java.math.BigDecimal;):

BigDecimal input = new BigDecimal(String.valueOf(3.4586748547d));
double output = input.setScale(2, BigDecimal.ROUND_FLOOR).doubleValue();
System.out.println(output);

You can also use regex for that purpose, like below:

String inputString = String.valueOf(3.4586748547d);
String outputString = inputString.replaceAll("(\\d \\.\\d{2})\\d ", "$1");
System.out.println(outputString);
  • Related