2

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...

KnuturO
  • 1,565
  • 15
  • 19
Alex Lee
  • 71
  • 4
  • 1
    Does this answer your question? [Round to at most 2 decimal places (only if necessary)](https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary) – David784 Feb 27 '20 at 23:37
  • 1
    [*Math.round*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) rounds to the nearest integer, second or additional arguments are ignored. [*number.toFixed*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) returns a string. Please post valid javascript (e.g. what the PHP generates) or tag as PHP. Also sample input, expected output and actual output. – RobG Feb 27 '20 at 23:37
  • worse case, whatever the language, you can always use a standard round with something like (round(x*100))/100... with an extra conversion to int if the round didn't do it. – B. Go Mar 01 '20 at 21:06

3 Answers3

1

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); "
Dean Van Greunen
  • 5,060
  • 2
  • 14
  • 28
1

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);
Alex Lee
  • 71
  • 4
0

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

AlexM88
  • 194
  • 3
  • 14