This might be a strange question, but how do i truncatean array of floats to e.g.: 0.2f (2 decimal places).

Imagine i have a float array X that contains 10 elements with the value 2.123456. I want to make them 2.123.

Can anybody help?

Kind regards

有帮助吗?

解决方案

Look at the following code:

public class Truncate {
  public static void main(String[] args) {
    System.out.println(truncate(2.123556f));
  }

  public static float truncate(float f) {
    // after casting it to int, it will remove all decimal values.
    // float bigInt = (int) (Math.round(f * 1000)); // prints 2.124 for f=2.123556f
    float bigInt = (int) (f * 1000); // prints 2.123 for f=2.123556f
    float result = bigInt / 1000;

    return result;
  }
}

You can create your own truncate method or use a round if needed. That way you will force it to be 3 decimals. If you need it dynamically then you will need to play with the "1000"

It does not matter if it is an array or a float, just loop the array to call your truncate method.

UPDATE:

Maybe not the most elegant but you can use big decimals like this...

import java.math.BigDecimal;

public class Truncate {
  public static void main(String[] args) {
    System.out.println(truncate(new BigDecimal(0.13642351627349847f)));
  }
  public static BigDecimal truncate(BigDecimal number) {
    BigDecimal thousand = new BigDecimal(1000);
    BigDecimal mult = new BigDecimal(number.multiply(thousand).intValue()); 
    BigDecimal result = mult.divide(thousand);
    return result;
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top