0

I have a column that contain double value 42.2223. I want to truncate the last four digits of this particular column.

Can any one please provide hive UDF for this particular scenario?

2 Answers2

0

If you want to truncate the last four digits and get an integer, you can use the built-in functions floor(double a) or ceiling(double a), depending on the the kind of rounding (upper or lower) that you want.

If you wanted your double to be truncated to d decimal places (and get a double, instead of an integer), you could use round(double a, int d).

EDITED

In order to round without truncating, you can use this

CAST((column * 100) AS int)/100

Jaime Caffarel
  • 2,401
  • 4
  • 30
  • 42
0

Wrote an UDF for the above question where we can specify number of characters it can be truncated

package com.hive.udf.truncate;
import java.math.BigDecimal;
import org.apache.hadoop.hive.ql.exec.UDF;
public class Trunc extends UDF {
    public double evaluate(double input,int numberOfDecimals){
       if ( input > 0) {
         return new BigDecimal(String.valueOf(input)).setScale(numberOfDecimals, BigDecimal.ROUND_FLOOR).doubleValue();
            } 
       else {
         return new BigDecimal(String.valueOf(input)).setScale(numberOfDecimals, BigDecimal.ROUND_CEILING).doubleValue();
        }
    }
}