简体   繁体   中英

Round a number to 2 decimal places JS

I have

oninput="
    price_<?php echo esc_attr( $range_slider_id ); ?>.value=parseFloat(<?php echo esc_attr( $range_price_id ); ?>)*parseFloat(<?php echo esc_attr( $range_slider_id ); ?>.value); "

how to round price_~.value two decimal places?

I have on output:

<output id="price_range_5e5851cd67084" for="range_5e5851cd67084">43.199999999999996</output>

I have tried to add .toFixed(2) and .round(2) .. but it doesn't help...

use toFixed(2)

such as

oninput="
    price_<?php echo esc_attr( $range_slider_id ); ?>.value=parseFloat(<?php echo esc_attr( $range_price_id ).toFixed(2); ?>)*parseFloat(<?php echo esc_attr( $range_slider_id ); ?>.value).toFixed(2); "

found solution from this topic Why can't I use toFixed on an HTML input object's value? the final result:

price_<?php echo esc_attr( $range_slider_id ); ?>.value=Number(<?php echo esc_attr( $range_price_id ); ?>)*Number(<?php echo esc_attr( $range_slider_id ); ?>.value); price_<?php echo esc_attr( $range_slider_id ); ?>.value=Number(price_<?php echo esc_attr( $range_slider_id ); ?>.value).toFixed(2);

If it is just to display the number you can use:

number.toLocaleString('en', {minimumFractionDigits: 2, maximumFractionDigits: 2})

You can also replace 'en' with your preferred locale https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Locale

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM