Java에서 소수점 이하 두 자리까지만 두 배로자를 수 있습니까?
이 질문에 이미 답변이 있습니다.
예를 들어 3.545555555 변수가 있는데 3.54로 자르고 싶습니다.
표시 목적으로 원하는 경우 다음을 사용하십시오 java.text.DecimalFormat
.
new DecimalFormat("#.##").format(dblVar);
계산에 필요한 경우 다음을 사용하십시오 java.lang.Math
.
Math.floor(value * 100) / 100;
DecimalFormat df = new DecimalFormat(fmt);
df.setRoundingMode(RoundingMode.DOWN);
s = df.format(d);
사용 가능한 확인 RoundingMode
및 DecimalFormat
.
Bit Old Forum, 위의 답변 중 어느 것도 양수 및 음수 값 모두에 대해 작동하지 않았습니다 (나는 계산을 의미하고 반올림하지 않고 자르기를 의미합니다). 로부터 어떻게 자바에서 n 개의 소수 자릿수로 숫자를 반올림하는 링크
private static BigDecimal truncateDecimal(double x,int numberofDecimals)
{
if ( x > 0) {
return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_FLOOR);
} else {
return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_CEILING);
}
}
이 방법은 나를 위해 잘 작동했습니다.
System.out.println(truncateDecimal(0, 2));
System.out.println(truncateDecimal(9.62, 2));
System.out.println(truncateDecimal(9.621, 2));
System.out.println(truncateDecimal(9.629, 2));
System.out.println(truncateDecimal(9.625, 2));
System.out.println(truncateDecimal(9.999, 2));
System.out.println(truncateDecimal(-9.999, 2));
System.out.println(truncateDecimal(-9.0, 2));
결과 :
0.00
9.62
9.62
9.62
9.62
9.99
-9.99
-9.00
참고 먼저 그 double
진 부분이며, 정말하지 않습니다 이 소수점을.
당신이 장소를 진수 필요 경우 사용 BigDecimal
이있는, setScale()
잘라 내기위한 방법 또는 사용 DecimalFormat
를 얻을 수를 String
.
어떤 이유로, 당신이 사용하지 않는 경우, BigDecimal
당신은 당신을 캐스팅 할 수 double
에은 int
을 절단합니다.
Ones 위치 로 자르려면 다음을 수행하십시오 .
- 단순히 캐스팅
int
받는 사람 소수점 첫째 자리의 장소 :
- 10을 곱하다
- 캐스트
int
- 다시 캐스팅
double
- 10으로 나눕니다.
Hundreths 플레이스
- 100으로 곱하고 나눕니다.
예:
static double truncateTo( double unroundedNumber, int decimalPlaces ){
int truncatedNumberInt = (int)( unroundedNumber * Math.pow( 10, decimalPlaces ) );
double truncatedNumber = (double)( truncatedNumberInt / Math.pow( 10, decimalPlaces ) );
return truncatedNumber;
}
이 예에서, decimalPlaces
사람은 당신이 가고 싶은 이후 자리의 자릿수가 될 것이다, 그렇게 한 것 라운드에 에바의 장소, 2에 백분 등 (0으로 라운드에 사람의 장소, 그리고 수십 부정적 일 등)
어쩌면 Math.floor(value * 100) / 100
? 같은 값 3.54
은 double
.
NumberFormat Class 객체를 사용하여 작업을 수행 할 수 있습니다.
// Creating number format object to set 2 places after decimal point
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.setGroupingUsed(false);
System.out.println(nf.format(precision));// Assuming precision is a double type variable
3.545555555는 3.54를 얻습니다. 이를 위해 다음을 시도하십시오.
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.FLOOR);
double result = new Double(df.format(3.545555555);
이것은 3.54를 줄 것입니다!
내가 사용하는 방법은 다음과 같습니다.
double a=3.545555555; // just assigning your decimal to a variable
a=a*100; // this sets a to 354.555555
a=Math.floor(a); // this sets a to 354
a=a/100; // this sets a to 3.54 and thus removing all your 5's
다음과 같이 할 수도 있습니다.
a=Math.floor(a*100) / 100;
문자열로 형식을 지정하고 다시 double로 변환하면 원하는 결과를 얻을 수 있습니다.
double 값은 round (), floor () 또는 ceil ()이 아닙니다.
이에 대한 빠른 수정은 다음과 같습니다.
String sValue = (String) String.format("%.2f", oldValue);
Double newValue = Double.parseDouble(sValue);
표시 목적으로 sValue를 사용하거나 계산을 위해 newValue를 사용할 수 있습니다.
Maybe following :
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
A quick check is to use the Math.floor method. I created a method to check a double for two or less decimal places below:
public boolean checkTwoDecimalPlaces(double valueToCheck) {
// Get two decimal value of input valueToCheck
double twoDecimalValue = Math.floor(valueToCheck * 100) / 100;
// Return true if the twoDecimalValue is the same as valueToCheck else return false
return twoDecimalValue == valueToCheck;
}
I have a slightly modified version of Mani's.
private static BigDecimal truncateDecimal(final double x, final int numberofDecimals) {
return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_DOWN);
}
public static void main(String[] args) {
System.out.println(truncateDecimal(0, 2));
System.out.println(truncateDecimal(9.62, 2));
System.out.println(truncateDecimal(9.621, 2));
System.out.println(truncateDecimal(9.629, 2));
System.out.println(truncateDecimal(9.625, 2));
System.out.println(truncateDecimal(9.999, 2));
System.out.println(truncateDecimal(3.545555555, 2));
System.out.println(truncateDecimal(9.0, 2));
System.out.println(truncateDecimal(-9.62, 2));
System.out.println(truncateDecimal(-9.621, 2));
System.out.println(truncateDecimal(-9.629, 2));
System.out.println(truncateDecimal(-9.625, 2));
System.out.println(truncateDecimal(-9.999, 2));
System.out.println(truncateDecimal(-9.0, 2));
System.out.println(truncateDecimal(-3.545555555, 2));
}
Output:
0.00
9.62
9.62
9.62
9.62
9.99
9.00
3.54
-9.62
-9.62
-9.62
-9.62
-9.99
-9.00
-3.54
This worked for me:
double input = 104.8695412 //For example
long roundedInt = Math.round(input * 100);
double result = (double) roundedInt/100;
//result == 104.87
I personally like this version because it actually performs the rounding numerically, rather than by converting it to a String (or similar) and then formatting it.
//if double_v is 3.545555555
String string_v= String.valueOf(double_v);
int pointer_pos = average.indexOf('.');//we find the position of '.'
string_v.substring(0, pointer_pos+2));// in this way we get the double with only 2 decimal in string form
double_v = Double.valueOf(string_v);//well this is the final result
well this might be a little awkward, but i think it can solve your problem :)
'Program Tip' 카테고리의 다른 글
두 개의 NSNumber 객체를 추가하는 방법은 무엇입니까? (0) | 2020.10.13 |
---|---|
Mongoose를 사용하여 MongoDB 문서에서 키 삭제 (0) | 2020.10.13 |
{m} {n} ( '정확히 n 번'두 번)은 어떻게 작동하나요? (0) | 2020.10.13 |
매개 변수가 일정 할 수 있습니까? (0) | 2020.10.12 |
라이브 MongoDB 데이터를 검색하거나 쿼리하려면 어떻게해야합니까? (0) | 2020.10.12 |