Home > Net >  Typescript subtraction with decimal numbers
Typescript subtraction with decimal numbers

Time:12-01

I have a table that tracks stock level changes, on most occasions the addition/subtraction is with whole numbers (-1, -2, 2, 3) etc. However, on some instances 0.5, -0.25 may be required. My current code get the correct values, but when it comes to decimals, it will on deduct or add to the nearest whole number ( 1/-1). The oldValue and newValue variable are populated from a stock changes table and I'm displaying the number of change from stock.

Below is the calculation function -

  formatDifference(change: StockChange) {
    const difference = parseInt(change.newValue || '0', 10) - parseInt(change.oldValue || '0', 10);
    return difference > 0 ? ' '   difference : difference;
  }

HTML -

<td style="text-align: center;">
  ({{formatDifference(change)}})
  <div class="stockLabel">
   Difference
  </div>
</td>

CodePudding user response:

Since you don't store the value, one possible way to do it in the HTML itself is with the decimal pipe (number is the keyword for decimal pipe)

<td style="text-align: center;">
  ( {{    (change?.newValue ?? 0 | number:'1.0-2') - 
          (change?.oldValue ?? 0 | number:'1.0-2')
          | number:'1.0-2'        
    }} )
  <div class="stockLabel">
   Difference
  </div>
</td>

Basic sintaxis:

{{value| number :'digits before decimal point . minimum number of digits after decimal point - maximum number of digits after decimal point' }}

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits} For instacen, '1.0-2' means:

  • A minimum of 1 digit will be show before decimal point
  • It doesn't have to have digits after decimal point (default)
  • If it has numbers after decimal point, the max is 2 digits

If you want to pass "the logic" to the ts file, you also can use the decimalPipe programmatically, but you have to import it in your file and then use it as "decimalPipe":

import {DecimalPipe} from '@angular/common';
...
constructor( private decimalPipe: DecimalPipe ) { }
...
formatDifference(change: StockChange) {
    const difference = this.decimalPipe.transform( change.newValue || '0', '1.0-2') - this.decimalPipe.transform( change.oldValue || '0', '1.0-2');
    return difference > 0 ? ' '   difference : difference;
  }

NOTE: The decimal pipe is in de '@angular/common', so you need to have it imported in your module.

More info about decimal pipe HERE

CodePudding user response:

Try this:

The function convert both values to numbers with fixed 2 decimals to do the substraction

const formatDifference = (change: StockChange): string => {
    let newValue =  Number(change.newValue ?? "0").toFixed(2);
    let oldValue =  Number((change.oldValue ?? "0")).toFixed(2);
    const difference = newValue - oldValue;
    return difference > 0 ? ` ${difference}` : difference   "";
}
  • Related