Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

xml - XSL - rounding/format-number problem

I'm trying to get the value of a number to 2 dec places from my xml.

XML:<Quantity>0.0050</Quantity>

XSL:<xsl:value-of select="format-number($quantity, '####0.00')" />

However XSL seems to have a problem with this value and outputs 0.00 in one area of the page and 0.01 in the other. Of course in this situation it is favourable to have 0.01 output in all areas.

Another area has the value 4.221 yet the XSL is outputting 4.23.

I do realise that format-number as a method converts a number to a string.

Not sure how to fix this.


EDIT:

Ok after a bit of mucking around i found that this works:

<xsl:value-of select='format-number( round(100*$quantity) div 100 ,"##0.00" )' />

Via this website

As this guy mentions XSL uses 'bankers rounding' to round to even numbers instead of the bigger ones.

The solution hardly seems elegant, and means adding a ton of extra functions to an already bulky and complicated XSL file. Surely i'm missing something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not sure why format would be so inconsistent but from memory the spec for it is...complex.

Meantime, you can use the round function (ref). Which is less than perfect, but is functional. If you need to have a particular number of sig figs you can use THE POWER OF MATHS! and do something like:

<xsl:value-of select="round(yournum*100) div 100"/>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...