Numbas icon indicating copy to clipboard operation
Numbas copied to clipboard

Display 2 decimals when simplifying

Open YannickNeyt opened this issue 5 years ago • 4 comments

I'm making a question about money, and I'd like simplified numbers to be displayed with exactly 2 decimals, as most prices are.

Something like: $\simplify[decimals=2]{{p1}+{p2}}$ outputting $2.20$ if p1=1.05 and p2=1.15 would be nice.

YannickNeyt avatar Dec 16 '20 12:12 YannickNeyt

That's a good suggestion, thanks.

For now, you could use the dpformat or currency functions? You won't get simplification rules applied, so you'll need to beware of things like adding negative numbers.

christianp avatar Dec 16 '20 12:12 christianp

Thanks, that seems to work fine in most cases, except when the amount is less than 1. Something like {currency(a,'','')} or $\var{latex(currency(a,'',''))}$ for a=0.80 outputs 80 or $80$ instead.

YannickNeyt avatar Dec 18 '20 10:12 YannickNeyt

The currency function prefers to render numbers less than 1 using the 'cents' symbol, which is the third argument. For example, currency(0.8,'£','p') would produce 80p. I think dpformat does what you want.

I do want to implement the [decimals=2] option you suggested, so I'm leaving this open.

christianp avatar Jan 04 '21 13:01 christianp

I missed your mention of dpformat... I made a custom function based on currency: (the number n is the only input)

var s = Numbas.math.niceNumber(100*n,{precisionType:'dp',precision:0}); if(n >=0.995){ if(n%1 < 0.005) { return Numbas.math.niceNumber(Math.floor(n)); } else if(n%1 >= 0.995) { return Numbas.math.niceNumber(Math.ceil(n)); } s = s.replace(/(..)$/,'.$1'); // put a dot before the last two digits, representing the cents return s } else { s = s.replace(/(..)$/,'0.$1'); // put 0. before the last two digits, representing the cents return s
}

YannickNeyt avatar Jan 06 '21 09:01 YannickNeyt