1

I'm creating shop app and i have problem with my number pipe. Is there any way to enable format number like 64,90 to set two digits after the decimal point only if there's value in db like 64.9 and if it's 60 in db, to show only 60 without digits after ?

<p>{{ product.price | number: '1.2-2' }} zł</p>

This pipe shows my correct 64.90 but not correct 60.00

  • Not sure about the capabilities of the number pipe syntax itself, but you could easily fix this issue with two if statements: `

    -1">{{ product.price | number: '1.2-2' }}{{ product.price }}

    `
    – enf0rcer Mar 21 '18 at 20:49
  • Why would you want to alter between having decimal places and not - doesn't sound like very good UX design imo. – Zze Mar 21 '18 at 20:53
  • @user3492940 indexOf is not a method –  Mar 21 '18 at 20:58

1 Answers1

1

You can write your own pipe like this:

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

@Pipe({
  name: 'floatNumbers'
})
export class FloatNumbersPipe implements PipeTransform {
  transform(value: string): string {
    const isFloat = (n) => {
      return n === +n && n !== (n|0);
    }

    return isFloat(+value) ? (+value).toFixed(2) : value;
  }
}
Patryk Gułaś
  • 847
  • 1
  • 7
  • 19
  • Many thanks! But can u actually write what this return is doing? It's working but i have problem with understanding that –  Mar 21 '18 at 21:02
  • 1
    It's if shorthand. We check if value (we need to parse it to number by adding +) is float, if so - we return that value with two decimals places (we need also to parse it to number to get toFixed method) in otherwise we just return that value. Here you are! – Patryk Gułaś Mar 21 '18 at 21:06
  • Actually i was asking about this: n === +n && n !== (n|0) this is so hard for me to understand. I see two condiditions here but dk what is happening there –  Mar 21 '18 at 21:09
  • 1
    It's function from here https://stackoverflow.com/a/3885844/3986118 You can check all discussion for better understanding. – Patryk Gułaś Mar 21 '18 at 21:18