开发者

numbers after comma in Java

开发者 https://www.devze.com 2023-03-01 14:51 出处:网络
How do I get n numbers after a comm开发者_开发问答a in Java? ... double numb = 123.45; void lastNumber(int n){

How do I get n numbers after a comm开发者_开发问答a in Java?

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

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


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.)


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

or make use of

  • BigDecimal


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 the BigDecimal 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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号