0

Hi I am trying to round the number I calculated to thousand's place.

For example, If I got 545,000 I want it to be 550,000

I created a pipe

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

@Pipe({name: 'round'})
export class RoundPipe implements PipeTransform {

    transform(value: number): number {
        return Math.round(value);
    }
}

Doesn't seem to work

Any idea?

4
  • Pipe did not work or logic? are you getting an error? post the code where you have applied hte pipe Commented Jul 12, 2017 at 1:26
  • no it doesnt give me the number I want maybe coz I didn't set it to calculate to thousand's digit ?
    – Lea
    Commented Jul 12, 2017 at 1:28
  • Yours business logic is unique to your case, don't expect a general function call (Math.round(value)) to fit all special cases.
    – Harry Ninh
    Commented Jul 12, 2017 at 1:30
  • that's why I'm asking how to fit my unique case :) I
    – Lea
    Commented Jul 12, 2017 at 1:33

3 Answers 3

6

You need to pass another parameter to the pipe giving the number of digits to round to, so it would be called as

{{value | round:4}}

pick it up in the argument list to transform

transform(value: number, digits: number): number {

and then do the right calculation inside your pipe logic, which would be something like

Math.round(value / (10 ** digits)) * (10 ** digits)
0
3

This is just simple rounding logic. If the value is less than value%1000 round down, otherwise round up.

var toNearest = 10000;
var mod = value % toNearest;
return mod < toNearest/2 ? 
    value - mod :             //round down
    value + (toNearest-mod);  //round up
3
Try this =====

import {Pipe} from '@angular/core';

@Pipe({name: 'round'})
export class RoundPipe {
  transform (input:number) {
    return Math.round(input);
  }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.