반응형
반응형
반응형

java 소수점 처리

 - 데이터 타입이 float 이나 double 이어야 합니다.

 

ex) 나누기 연산을 해서 소수 둘째자리까지 출력하는 방법.

1. String.format

 - 반올림 된 값으로 결과값 출력.

 - 소수점 자릿수 지정(고정)

private static void div(int mb) {
        double gb = (double)mb / 1024;
        System.out.println("\n---------------------------------");
        System.out.println("" + mb + " / 1024 = " + gb);

        System.out.println("String.format = " + String.format("%.2f", gb));
}

div(1024);
div(1540);
div(1550);
div(1400);


결과 :
---------------------------------
1024 / 1024 = 1.0
String.format = 1.00

---------------------------------
1540 / 1024 = 1.50390625
String.format = 1.50

---------------------------------
1550 / 1024 = 1.513671875
String.format = 1.51

---------------------------------
1400 / 1024 = 1.3671875
String.format = 1.37

 

2. BigDecimal

 - 반올림/올림/내림 설정 가능.

 - 소수점 자릿수 지정(고정 / 마지막이 0 인 경우 버림 가능)

private static void div(int mb) {
        double gb = (double)mb / 1024;
        System.out.println("\n---------------------------------");
        System.out.println("" + mb + " / 1024 = " + gb);

        BigDecimal bdMb = new BigDecimal(mb);
        BigDecimal bdKb = new BigDecimal(1024);
        System.out.println("BigDecimal = " + bdMb.divide(bdKb, 2, RoundingMode.DOWN));
        System.out.println("BigDecimal(stripTrailingZeros) = " + bdMb.divide(bdKb, 2, RoundingMode.DOWN).stripTrailingZeros());
}
    
div(1024);
div(1540);
div(1550);
div(1400);


---------------------------------
1024 / 1024 = 1.0
BigDecimal = 1.00
BigDecimal(stripTrailingZeros) = 1

---------------------------------
1540 / 1024 = 1.50390625
BigDecimal = 1.50
BigDecimal(stripTrailingZeros) = 1.5

---------------------------------
1550 / 1024 = 1.513671875
BigDecimal = 1.51
BigDecimal(stripTrailingZeros) = 1.51

---------------------------------
1400 / 1024 = 1.3671875
BigDecimal = 1.36
BigDecimal(stripTrailingZeros) = 1.36

 

3. DecimalFormat

 - 반올림 된 값으로 결과값 출력.

 - 소수점 자릿수 지정(고정 / 마지막이 0 인 경우 버림 가능 / 0 버림 갯수 지정 가능)

private static void div(int mb) {
        double gb = (double)mb / 1024;
        System.out.println("\n---------------------------------");
        System.out.println("" + mb + " / 1024 = " + gb);

        DecimalFormat formatter = new DecimalFormat("0.##");
        System.out.println("DecimalFormat(0.##) = " + formatter.format(gb));

        DecimalFormat formatter2 = new DecimalFormat("0.0#");
        System.out.println("DecimalFormat(0.0#) = " + formatter2.format(gb));
}

div(1024);
div(1540);
div(1550);
div(1400);


결과 :
---------------------------------
1024 / 1024 = 1.0
DecimalFormat(0.##) = 1
DecimalFormat(0.0#) = 1.0

---------------------------------
1540 / 1024 = 1.50390625
DecimalFormat(0.##) = 1.5
DecimalFormat(0.0#) = 1.5

---------------------------------
1550 / 1024 = 1.513671875
DecimalFormat(0.##) = 1.51
DecimalFormat(0.0#) = 1.51

---------------------------------
1400 / 1024 = 1.3671875
DecimalFormat(0.##) = 1.37
DecimalFormat(0.0#) = 1.37

 

4. DecimalFormat + BigDecimal

 - 반올림 된 값으로 결과값 출력.

 - 소수점 자릿수 지정(고정 / 마지막이 0 인 경우 버림 가능 / 0 버림 갯수 지정 가능)

private static void div(int mb) {
        double gb = (double)mb / 1024;
        System.out.println("\n---------------------------------");
        System.out.println("" + mb + " / 1024 = " + gb);

        DecimalFormat formatter = new DecimalFormat("0.##");
        DecimalFormat formatter2 = new DecimalFormat("0.0#");
        System.out.println("DecimalFormat(BigDecimal, 0.##) = " + formatter.format(bdMb.divide(bdKb, 2, RoundingMode.DOWN)));
        System.out.println("DecimalFormat(BigDecimal, 0.0#) = " + formatter2.format(bdMb.divide(bdKb, 2, RoundingMode.DOWN)));
}
    
div(1024);
div(1540);
div(1550);
div(1400);
        

결과 :
---------------------------------
1024 / 1024 = 1.0
DecimalFormat(BigDecimal, 0.##) = 1
DecimalFormat(BigDecimal, 0.0#) = 1.0

---------------------------------
1540 / 1024 = 1.50390625
DecimalFormat(BigDecimal, 0.##) = 1.5
DecimalFormat(BigDecimal, 0.0#) = 1.5

---------------------------------
1550 / 1024 = 1.513671875
DecimalFormat(BigDecimal, 0.##) = 1.51
DecimalFormat(BigDecimal, 0.0#) = 1.51

---------------------------------
1400 / 1024 = 1.3671875
DecimalFormat(BigDecimal, 0.##) = 1.36
DecimalFormat(BigDecimal, 0.0#) = 1.36

 

반응형
반응형

Java Stream reduce 함수에 대한 설명입니다.

 

바로 소스로 들어가보자!

import java.util.OptionalInt;
import java.util.stream.IntStream;

public class StreamReduce {

    public static void main(String[] args) {
        //Optional<T> reduce(BinaryOperator<T> accumulator);
        OptionalInt reduced1 = IntStream.range(1, 5) // [1, 2, 3, 4]
                        .reduce((a, b) -> {
                            System.out.println("a = " + a);
                            System.out.println("b = " + b);
                            return Integer.sum(a, b);
                        });

        System.out.println(reduced1.getAsInt());


        //T reduce(T identity, BinaryOperator<T> accumulator);
        int reduced2 = IntStream.range(1, 5) // [1, 2, 3, 4]
                        .reduce(10, (a, b) -> {
                            System.out.println("a = " + a);
                            System.out.println("b = " + b);
                            return Integer.sum(a, b);
                        });

        System.out.println(reduced2);
    }
}

 

긴말 필요 없이 결과도 바로 확인해보자!

a = 1
b = 2
a = 3
b = 3
a = 6
b = 4
10

a = 10
b = 1
a = 11
b = 2
a = 13
b = 3
a = 16
b = 4
20

 

Stream 생성 했던 IntStream 의 range 함수는 Javadoc 으로 확인해본다.

IntStream (Java Platform SE 8 ) (oracle.com)

 

IntStream (Java Platform SE 8 )

Returns an infinite sequential ordered IntStream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc. The first element (position 0) in the IntStream will be the prov

docs.oracle.com

 

※ 첫번째 파라미터는 포함, 두번째 파라미터는 불포함

 - 항상 헷갈리는 부분이니까 꼼꼼히 읽어보자!!

static IntStream range(int startInclusive, int endExclusive)
Returns a sequential ordered IntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1.
API Note:
An equivalent sequence of increasing values can be produced sequentially using a for loop as follows:

     for (int i = startInclusive; i < endExclusive ; i++) { ... }
 
Parameters:
startInclusive - the (inclusive) initial value
endExclusive - the exclusive upper bound
Returns:
a sequential IntStream for the range of int elements

 

 

자, 이제 본격적으로 Stream reduce 에 대한 설명 들어보고 가실께여~

1. 먼저 파라미터가 1개인 reduce 함수

        //Optional<T> reduce(BinaryOperator<T> accumulator);
        OptionalInt reduced1 = IntStream.range(1, 5) // [1, 2, 3, 4]
                        .reduce((a, b) -> {
                            System.out.println("a = " + a);
                            System.out.println("b = " + b);
                            return Integer.sum(a, b);
                        });

        System.out.println(reduced1.getAsInt());

첫번째 실행

 - a : Stream 의 첫번째 값 = 1

 - b : Stream 의 두번째 값 = 2

 - a + b = 3 을 반환(return) 한다.

두번째 실행

 - a : 첫번째 실행한 결과 값 = 3

 - b : Stream 의 다음(세번째) 값 = 3

 - a + b = 6 을 반환(return) 한다.

세번째 실행

 - a : 두번째 실행한 결과 값 = 6

 - b : Stream 의 다음(네번째) 값 = 4

 - a + b = 10 을 반환(return) 한다.

최종 실행 결과 값으로 10을 반환한다.

 

2. 먼저 파라미터가 2개인 reduce 함수

 - reduce 함수의 첫번째 파라미터는 초기 값을 의미한다.

        //T reduce(T identity, BinaryOperator<T> accumulator);
        int reduced2 = IntStream.range(1, 5) // [1, 2, 3, 4]
                        .reduce(10, (a, b) -> {
                            System.out.println("a = " + a);
                            System.out.println("b = " + b);
                            return Integer.sum(a, b);
                        });

        System.out.println(reduced2);

 

첫번째 실행

 - a : 초기 값 = 10

 - b : Stream 의 첫번째 값 = 1

 - a + b = 11 을 반환(return) 한다.

두번째 실행

 - a : 첫번째 실행한 결과 값 = 11

 - b : Stream 의 다음(두번째) 값 = 2

 - a + b = 13 을 반환(return) 한다.

세번째 실행

 - a : 두번째 실행한 결과 값 = 13

 - b : Stream 의 다음(세번째) 값 = 3

 - a + b = 16 을 반환(return) 한다.

네번째 실행

 - a : 세번째 실행한 결과 값 = 16

 - b : Stream 의 다음(네번째) 값 = 4

 - a + b = 20 을 반환(return) 한다.

최종 실행 결과 값으로 20을 반환한다.

 

 

위에서 살펴본 Stream reduce 두 함수의 차이는 초기 값이 있냐 없냐의 차이이다.

그리고 Stream reduce 함수에서 가장 중요하게 봐야할 부분은 accumulator 의 동작 방식이다.

첫번째, 두번째 인자에 값이 어떻게 전달되어 최종 결과값을 반환하는지에 대한 이해만 있다면 어렵지 않을 것이다.

 

Stream reduce 에 대한 Javadoc 페이지도 같이 확인하면 좋을 것 같아 링크를 건다.

Stream (Java Platform SE 8 ) (oracle.com)

 

Stream (Java Platform SE 8 )

A sequence of elements supporting sequential and parallel aggregate operations. The following example illustrates an aggregate operation using Stream and IntStream: int sum = widgets.stream() .filter(w -> w.getColor() == RED) .mapToInt(w -> w.getWeight())

docs.oracle.com

 

반응형
반응형


===============================================================
== C:\javadev\programs\tomcat-5.5.23\conf\web.xml 파일 수정. ==
===============================================================
주석을 해제해야 하는 부분 : 2군데.

1.

    <servlet>
        <servlet-name>invoker</servlet-name>
        <servlet-class>
          org.apache.catalina.servlets.InvokerServlet
        </servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>

 

2.

    <servlet-mapping>
        <servlet-name>invoker</servlet-name>
        <url-pattern>/servlet/*</url-pattern>
    </servlet-mapping>

 

 

===============================================================
== Project Properties 수정 : servlet Library 추가. ============
===============================================================

Project -> Properties -> Java Build Path -> Source
 - Default output folder : Project Name/WebContent/WEB-INF/classes


Project -> Properties -> Java Build Path -> Libraries
 - Add External JARs... : C:\javadev\programs\tomcat-5.5.23\common\lib\servlet-api.jar

 

 

=============================================================
== jstl 사용시 추가.
=============================================================
jstl.jar
standard.jar

 


=============================================================
== java application library path 와 sevlet library path 는 다르다.
=============================================================

 

 

반응형

'프로그래밍 > Java' 카테고리의 다른 글

abstract 와 interface 의 차이.  (0) 2009.06.05
ajax, jsp 에서 한글 깨짐 문제.  (1) 2009.04.23
[xml] xml parsing - SAXParseException  (0) 2009.03.13
inputStream <-> String  (0) 2009.03.03
jstl 예제 - fn, fmt, foreach  (2) 2009.02.18

+ Recent posts