0

I have decimal numbers like this 0.00651536 and I am unable to validating this number to see if its greater than other decimal number (e.g: 0.00651537) or not!

here is an example:

//$request->input('price') = 0.00651537
//$product->price = 0.00651536

if($request->input('price') > $product->price) {
  // my input is greater than product price
} else {
  // my input is not greater than product price
}

Issue: (Update)

As my $product->price is decimal starting with 0. it just keep looking to that 0 and does not validate rest of it while my input number difference with product price is in decimals.

How can I validate my numbers?

PS: These are just sample numbers therefore decimals could be shorter or longer (don't go with this example length)

mafortis
  • 6,750
  • 23
  • 130
  • 288
  • Your logic is working, so what seems to be the issue??? – Anuga Dec 22 '22 at 10:27
  • @Anuga this if statement has else part and it always return else part unless i input an integer (not decimal number) – mafortis Dec 22 '22 at 10:29
  • My read this: https://stackoverflow.com/questions/3148937/compare-floats-in-php – Foobar Dec 22 '22 at 10:33
  • Does this answer your question? [Compare floats in php](https://stackoverflow.com/questions/3148937/compare-floats-in-php) – Justinas Dec 22 '22 at 10:35
  • @Justinas no, I've just tried `floatval( (string) xxxx)` didn't work – mafortis Dec 22 '22 at 10:37
  • This is your code written to be executable: https://3v4l.org/m9IhC Clearly there's something else going on you haven't told us about. – KIKO Software Dec 22 '22 at 10:37
  • 1
    What is the output when you `var_dump` both `$request->input('price')` and `$product->price`? – RJK Dec 22 '22 at 10:46
  • @KIKOSoftware this is what I'm getting in my test `{"input":0.00651545,"product":0.00651536,"result":false}` – mafortis Dec 22 '22 at 10:47
  • @RJK My values are strings so I added `(float)` in front of each one like this `(float)$request->input('price')` and `(float)$product->price` – mafortis Dec 22 '22 at 10:48
  • 1
    To really be able to help you we would need a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example), but you already know that. Why can't you provide one? – KIKO Software Dec 22 '22 at 10:50
  • @KIKOSoftware It somehow just worked!!! i will retry this later if it still gave error I make sure to share with you controller function completely. thanks again (let see if it keeps working!) – mafortis Dec 22 '22 at 10:52

1 Answers1

2

Have you tried converting it to float?

You can try something like:

   if(floatval($request->input('price')) > floatval( $product->price)) {
  // my input is greater than product price
} else {
  // my input is not greater than product price
}
Romina2426
  • 21
  • 1
  • Yes https://stackoverflow.com/questions/74887112/check-decimal-numbers-in-laravel/74887674#comment132157524_74887112 – mafortis Dec 24 '22 at 10:56