Tell us what you are trying to do?
I'd like to round a number to 2 decimal places
This means that if the number is 3 decimal places or more, it should round to 2 decimal places.
It also means that if someone enters 1 decimal place, then a zero should be added.
Is there a standard function as part of Views?
Minesh
Supporter
Languages:
English (English )
Timezone:
Asia/Kolkata (GMT+05:30)
Hello. Thank you for contacting the Toolset support.
Well - to round the number to two decimal places, you need to create custom shortcode and add it to your current theme's functions.php file.
Please try to add following code to your current theme's functions.php file:
add_shortcode('round_the_number', function( $atts = [], $content=null ) {
$atts = shortcode_atts( array('round' => 0 ), $atts );
$content = wpv_do_shortcode($content);
return round($content, $atts['round']);
});
Call the shortcode as given under:
[round_the_number round='2']
[types field="your-field-name"]
[/round_the_number]
Hi - Thanks for that.
A couple of questions...
Did you mean:
[round_the_number round='2'][types field="price"][/types][/round_the_number]
(with the [/types] - as the editor didn't seem to want to accept it without.
I have the field set up as a number, as per the screen shot here: hidden link
It still doesn't seem to work (see: the right hand column under price here: hidden link )
Thanks!
Stephanie
Minesh
Supporter
Languages:
English (English )
Timezone:
Asia/Kolkata (GMT+05:30)
The placeholder is the simple text or anything that will take place when field value is empty.
How do you want to display the following price?
0.12 USD
1.42 SGD
5 MYR
As per my original request (which I am re-including below with examples):
I'd like to round a number to 2 decimal places
This means that if the number is 3 decimal places or more, it should round to 2 decimal places.
eg. 2.346 should round to 2.35
It also means that if someone enters 1 decimal place, then a zero should be added.
eg. 1.2 should become 1.20
So following a similar rule, 5 should be 5.00
Minesh
Supporter
Languages:
English (English )
Timezone:
Asia/Kolkata (GMT+05:30)
ok - please try to use following code and try to resolve your issue:
add_shortcode('round_the_number', function( $atts = [], $content=null ) {
$atts = shortcode_atts( array('round' => 0 ), $atts );
$content = wpv_do_shortcode($content);
$number = round($content, $atts['round']);
return number_format($number,2);
});
To add zero you need to use number_format() function and I've adjusted the code as above and checked the conditions you shared and tested it and its working fine.
Could you please confirm it works at your end as well.
[round_the_number round='2'][types field="price"][/types][/round_the_number]
Very good. Many thanks.
I was thinking that this would have been a function as a part of number type, but this works. Thank you !