numbas / Numbas

A completely browser-based e-assessment/e-learning system, with an emphasis on mathematics
http://www.numbas.org.uk
Apache License 2.0
199 stars 118 forks source link

Display 2 decimals when simplifying #1050

Open YannickNeyt opened 3 years ago

YannickNeyt commented 3 years ago

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.

christianp commented 3 years ago

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.

YannickNeyt commented 3 years ago

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.

christianp commented 3 years ago

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.

YannickNeyt commented 3 years ago

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
}