简体   繁体   中英

numbers after comma in Java

How do I get n numbers after a comma in Java?

...
double numb = 123.45;
void lastNumber(int n){
   // here
}
...

(in this example n = 2, so two numbers after the comma)

  • multiply it by 10^n
  • floor or cast to int
  • divide it by 10^n

or make use of

  • BigDecimal

A bit ugly:

public long getFraction(double num, int digits) {
    int multiplier = POWERS_OF_TEN[digits];
    long result = ((long) (num * multiplier)) - (((long) num) * multiplier);
    return result;
}

where POWERS_OF_TEN is an array of precomputed powers of ten (0=1, 1=10, 2=100, 3=1000, etc.)

double numb = 123.45 isn't actually 123.45, but something quite close to it in binary representation.

If you need EXACTLY 123.45 you need theBigDecimal class, like

BigInteger numb = new BigInteger("123.45"); // or
BigInteger numb = BigInteger.valueOf(12345, 2);

A short working program yielding 45:

import java.math.BigDecimal;

public class Main {

    public static void main(String[] args) {
        BigDecimal numb = BigDecimal.valueOf(12345,2);
        BigDecimal remainder = numb.remainder(BigDecimal.ONE);
        System.out.println(remainder.unscaledValue());
    }
}

BigIntegers are no fun to work with, but are really nice when dealing with financials. They're not fast but if you have only one number that shouldn't be a problem:)

This is relatively simple. Rather than just give the answer, please think about this. Forget Java - think about what you want to do from a mathematics point of view. From the question, you want numbers after the decimal point - the fractional part of the number - 0.45 . How can you get 0.45 from 123.45?

Think about what you need to subtract, and how do you get that number? There is a math function, "floor", that gives you a number without its fractional part. (At least for positive numbers.)

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