RaulGM
RaulGM

Reputation: 342

How to truncate a number in Angular

I'm trying to make this operation inside an HTML file using Angular with TypeScript: {{(i / 5) % 3}}.

The problem is that when i / 5 does not return a natural number, it can't continue to operate the % 3 part. So the question is: How can I truncate the i / 5 in order to get an acceptable result for the operation?

By the way, I tried to use the JavaScript function Math.trunc(i / 5) but I get an error that says:

'Cannot read property trunc of undefined'

Upvotes: 7

Views: 22854

Answers (6)

Rod Talingting
Rod Talingting

Reputation: 1080

You can use Math.trunc

Math.trunc(1.4) // 1
Math.trunc(1.9) // 1

Upvotes: 1

Manisha
Manisha

Reputation: 1

Wrote the custom pipe for truncation

import { Pipe, PipeTransform } from '@angular/core';
import { DecimalPipe } from '@angular/common'

@Pipe({
    name: 'truncateNum'
})
export class TruncateNumberPipe extends DecimalPipe implements PipeTransform {
    transform(value: any, digitsInfo?: string): string | null {

        const NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
        const parts = digitsInfo.match(NUMBER_FORMAT_REGEXP);

        let maxFraction;

        if (parts === null) {
            throw new Error(`${digitsInfo} is not a valid digit info for number pipes`);
        }

        if (parts[5] != null) {  // max fraction digits
            maxFraction = parseIntAuto(parts[5]);
        }

        return maxFraction ? super.transform(truncateToDecimals(strToNumber(value), maxFraction), digitsInfo) : super.transform(value, digitsInfo);
    }

}

function parseIntAuto(text: string): number {
    const result: number = parseInt(text);
    if (isNaN(result)) {
        throw new Error('Invalid integer literal when parsing ' + text);
    }
    return result;
}

/**
* truncate to decimal place.
*/
function truncateToDecimals(num, dec) {
    const calcDec = Math.pow(10, dec);
    return Math.trunc(num * calcDec) / calcDec;
}
/**
* Transforms a string into a number (if needed).
*/
function strToNumber(value: number | string): number {
    // Convert strings to numbers
    if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) {
        return Number(value);
    }
    if (typeof value !== 'number') {
        throw new Error(`${value} is not a number`);
    }
    return value;
}

Upvotes: 0

user663031
user663031

Reputation:

This question has nothing to do with TypeScript. TypeScript provides no new operators or functions or ways to truncate a number. TypeScript is just a type layer on top of JavaScript.

This is an Angular issue. You cannot use Math (any other global variable) in a template. Your options are:

  • (~~(i/5)) % 3
  • (i/5 - (i/5) % 1) % 3
  • Calculate it in your TypeScript file

Upvotes: 2

KrishOnline
KrishOnline

Reputation: 516

I could not understand the question. However, you can try Math.floor(i/5) % 3. This will give erroneous result when you divide by a negative number.

Upvotes: 5

Ludwig
Ludwig

Reputation: 1272

Not sure if that is what you want. You could try to use a DecimalPipe:

{{((i / 5) | number:'1.0-0') % 3}}

But looks like the above is rounding.

Upvotes: 3

José Quinto Zamora
José Quinto Zamora

Reputation: 2118

You can use three different Math APIs.

Math.floor always gives you lowest number:

Math.floor( 1 / 5 ) // 0
Math.floor( 4 / 5 ) // 0

Math.ceil always gives you highest number:

Math.ceil( 1 / 5 ) // 1
Math.ceil( 4 / 5 ) // 1

Math.round gives you the one with most proximity:

Math.round( 1 / 5 ) // 0
Math.round( 4 / 5 ) // 1

Upvotes: 1

Related Questions