github.com/manicqin/nomad@v0.9.5/ui/app/helpers/format-percentage.js (about) 1 import { helper } from '@ember/component/helper'; 2 3 /** 4 * Percentage Calculator 5 * 6 * Usage: {{format-percentage count total="number" complement="number"}} 7 * 8 * Outputs the ratio as a percentage, where ratio is either 9 * `count / total` or `count / (count + complement)` 10 */ 11 export function formatPercentage(params, options = {}) { 12 const value = safeNumber(params[0]); 13 const complement = options.complement; 14 15 let ratio; 16 let total = options.total; 17 18 if (total !== undefined) { 19 total = safeNumber(total); 20 } else if (complement !== undefined) { 21 total = value + safeNumber(complement); 22 } else { 23 // Ensures that ratio is between 0 and 1 when neither total or complement are defined 24 total = value; 25 } 26 27 // Use zero instead of infinity when the divisor is zero 28 ratio = total ? value / total : 0; 29 30 return 0 < ratio && ratio < 0.01 ? '< 1%' : Math.round(ratio * 100) + '%'; 31 } 32 33 // If a value is not a number, treat it as zero 34 function safeNumber(value) { 35 return isNaN(value) ? 0 : +value; 36 } 37 38 export default helper(formatPercentage);